openpyxl act differently in different Operating systems - python

I have a python code producing report on xlsx format using openpyxl.
It starts with copying a template to a new file with different name, filling the data on it and finally save it with different name.
the template (which is in xlsx format of course) contains logo, when i run the code in Linux i get the output file with the logo as expected, but when i run the same code in Windows i get the output without the logo!
import openpyxl
import re
import shutil
import os
src = r'/app1/labreport_template.xlsx'
dst = r'/app1/labreport.xlsx'
shutil.copyfile(src, dst)
my_wb=openpyxl.load_workbook("app1/labreport.xlsx")
my_sheet = my_wb.active
##all selections and formatting run here##
##End_Of_Formatting_Output##
my_wb.save("/XP_2600/Reporting_21/labreport.xlsx")
zrc = r'/app1/labreport.xlsx'
dzz = r'/app1/' + idx + '.xlsx'
shutil.copyfile(zrc, dzz)
os.remove(zrc)
print('Successfully generated the report: ' + ' ' + dzz )
Windows version just have Windows paths, everything else still same exact as Linux version, any idea whats wrong ? thanks.

I found a workaround for this by adding this:
##Logo_Entry
logo = openpyxl.drawing.image.Image('logo.png')
logo.anchor = 'A1'
my_sheet.add_image(logo)
##Logo_End
Of course its not a solution, and i still wonder why openpyxl on Windows processing the file like this!,
but i add the workaround, maybe it help someone facing same issue.

Related

How to change a python code into an application to run in any folder that it is saved with the files that are in the same folder

Good Morning,
I have made a little python code to merge some excel files in an specific windows folder. How can I changing my python code to share with my coleagues in a way that they can run the script in any folder that they want and consequently do the changes in any folder that the script is save, I mean, they have to save the script file .exe in a folder to run with the files that are there. Could you help me? My code is working as I expected, but for save as .exe I need to take off the address folder that I put on the code and change for a place that will work in any place that my colleagues decide to save the file and I don't know how to do that.
Could you help me please.
appended_rods = []
for relatorio in os.listdir(r'C:\Users\henrique.fontenelle.N2018001432\Desktop\Rods 19052021'):
rod_merged = pd.read_excel(relatorio, header = [0])
extract_state = str(rod_merged.iloc[[],[0]])
start = extract_state.find("/") + len("/")
end = extract_state.find(" e suas")
state = extract_state[start:end]
extract_period = str(rod_merged.iloc[[],[0]])
start = extract_period.find("De: ") + len("De: ")
end = extract_period.find("21.")
period = extract_period[start:end]+"21"
rod = pd.read_excel(relatorio, header =[1])
rod["Regional"] = state
rod["Período"] = period
appended_rods.append(rod)
reformatedDataSheet = pd.concat(appended_rods, ignore_index=True)
relatorio = reformatedDataSheet.filter(items=['Origem / ROD', 'Categoria / ROD','Item / ROD','Quantidade','Unidade', 'Regional', 'Período'])
relatorio.to_excel(r'C:\Users\henrique.fontenelle.N2018001432\Desktop\Rods 19052021\gravacaoRodConsolidado.xlsx', index = False)
You can use the Path of __file__ to change your current working directory to wherever the file you're running is housed.
Let's say your file is /home/madronos/Documents/some_dir/some_program.py
import os
from pathlib import Path
os.chdir(Path(__file__).parent)
Your cwd would now be /home/madronos/Documents/some_dir, and your running .py would look for files locally within the some_dir.
In terms of making a .exe, look into auto-py-to-exe
There are different ways to convert python program to .exe but i would suggest you to use auto-py-to-exe.

Generate clickable link to a file (Python) [duplicate]

when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))

pandas.read_csv FileNotFoundError: File b'\xe2\x80\xaa<etc>' despite correct path

I'm trying to load a .csv file using the pd.read_csv() function when I get an error despite the file path being correct and using raw strings.
import pandas as pd
df = pd.read_csv('‪C:\\Users\\user\\Desktop\\datafile.csv')
df = pd.read_csv(r'‪C:\Users\user\Desktop\datafile.csv')
df = pd.read_csv('C:/Users/user/Desktop/datafile.csv')
all gives the error below:
FileNotFoundError: File b'\xe2\x80\xaaC:/Users/user/Desktop/tutorial.csv' (or the relevant path) does not exist.
Only when i copy the file into the working directory will it load correct.
Is anyone aware of what might be causing the error?
I had previously loaded other datasets with full filepaths without any problems and I'm currently only encountering issues since I've re-installed my python (via Anaconda package installer).
Edit:
I've found the issue that was causing the problem.
When I was copying the filepath over from the file properties window, I unwittingly copied another character that seems invisible.
Assigning that copied string also gives an unicode error.
Deleting that invisible character made any of above code work.
Try this and see if it works. This is independent of the path you provide.
pd.read_csv(r'C:\Users\aiLab\Desktop\example.csv')
Here r is a special character and means raw string. So prefix it to your string literal.
https://www.journaldev.com/23598/python-raw-string:
Python raw string is created by prefixing a string literal with ‘r’
or ‘R’. Python raw string treats backslash () as a literal character.
This is useful when we want to have a string that contains backslash
and don’t want it to be treated as an escape character.
$10 says your file path is correct with respect to the location of the .py file, but incorrect with respect to the location from which you call python
For example, let's say script.py is located in ~/script/, and file.csv is located in ~/. Let's say script.py contains
import pandas
df = pandas.read_csv('../file.csv') # correct path from ~/script/ where script.py resides
If from ~/ you run python script/script.py, you will get the FileNotFound error. However, if from ~/script/ you run python script.py, it will work.
I know following is a silly mistake but it could be the problem with your file.
I've renamed the file manually from adfa123 to abc.csv. The extension of the file was hidden, after renaming, Actual File name became abc.csv.csv. I've then removed the extra .csv from the name and everything was fine.
Hope it could help anyone else.
import pandas as pd
path1 = 'C:\\Users\\Dell\\Desktop\\Data\\Train_SU63ISt.csv'
path2 = 'C:\\Users\\Dell\\Desktop\\Data\\Test_0qrQsBZ.csv'
df1 = pd.read_csv(path1)
df2 = pd.read_csv(path2)
print(df1)
print(df2)
On Windows systems you should try with os.path.normcase.
It normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes. Raise a TypeError if the type of path is not str or bytes (directly or indirectly through the os.PathLike interface).
import os
import pandas as pd
script_dir = os.getcwd()
file = 'example_file.csv'
data = pd.read_csv(os.path.normcase(os.path.join(script_dir, file)))
If you are using windows machine. Try checking the file extension.
There is a high possibility of file being saved as fileName.csv.txt instead of fileName.csv
You can check this by selecting File name extension checkbox under folder options (Please find screenshot)
below code worked for me:
import pandas as pd
df = pd.read_csv(r"C:\Users\vj_sr\Desktop\VJS\PyLearn\DataFiles\weather_data.csv");
If fileName.csv.txt, rename/correct it to fileName.csv
windows 10 screen shot
Hope it works,
Good Luck
Try using os.path.join to create the filepath:
import os
f_path = os.path.join(*['C:', 'Users', 'user', 'Desktop', 'datafile.csv'])
df = pd.read_csv(f_path)
I was trying to read the csv file from the folder that was in my 'c:\'drive but, it raises the error of escape,type error, unicode......as such but this code works
just take an variable then add r to read it.
rank = pd.read_csv (r'C:\Users\DELL\Desktop\datasets\iris.csv')
df=pd.DataFrame(rank)
There is an another problem on how to delete the characters that seem invisible.
My solution is copying the filepath from the file windows instead of the property windows.
That is no problem except that you should fulfill the filepath.
Experienced the same issue. Path was correct.
Changing the file name seems to solve the problem.
Old file name: Season 2017/2018 Premier League.csv
New file name: test.csv
Possibly the whitespaces or "/"
I had the same problem when running the file with the interactive functionality provided by Visual studio. Switched to running on the native command line and it worked for me.
For my particular issue, the failure to load the file correctly was due to an "invisible" character that was introduced when I copied the filepath from the security tab of the file properties in windows.
This character is e2 80 aa, the UTF-8 encoding of U+202A, the left-to-right embedding symbol. It can be easily removed by erasing (hitting backspace or delete) when you've located the character (leftmost char in the string).
Note: I chose to answer because the answers here do not answer my question and I believe a few folks (as seen in the comments) might meet the same situation as I did. There also seems to be new answers every now and then since I did not mark this question as resolved.
I had similar problem when I was using JupyterLab + Anaconda, and used my browser to type stuff on IDE.
My problem was simpler - there was a very subtle typo error. I didn't have to use raw text - either escaping or using {{r}} string worked for me :). If you use Anaconda with Jupyter Lab, I believe the Kernel starts with where you open the notebook from i.e. the working directory is that top level folder.
data = pd.read_csv('C:\\Users\username\Python\mydata.csv')
This worked for me. Note the double "\\" in "C:\\" where the rest of the folders use only a single "\".

Use Python to launch Excel file

when i try
os.system("open " + 'myfile.xlsx')
i get the output '0'
similarly, trying
os.system("start excel.exe myfilepath")
gives the result 32512
I have imported os and system, and I'm on mac. How can I change this so it does actually launch that excel file? And out of curiosity, what do the numbers it prints out mean?
Thanks!
Just these two lines
import os
os.system("start EXCEL.EXE file.xlsx")
Provided that file.xlsx is in the current directory.
If you only want to open the excel application you could use subprocess:
import subprocess
subprocess.check_call(['open', '-a', 'Microsoft Excel'])
You can also use os and open a specific file:
import os
os.system("open -a 'path/Microsoft Excel.app' 'path/file.xlsx'")
If you on other hand want to open an excel file within python and modify it there's a number of packages to use as xlsxwriter, xlutils and openpyxl where the latter is prefered by me.
Another note, if you're on mac the excel application isn't .exe
On Windows 10, this works for me:
import os
full_path_to_file = "C:\blah\blah\filename.xlsx"
os.system(full_path_to_file)
Copy-pasting any full path to a file in the command prompt (or passing it to os.system()) seems to work as long as you have permission to open the file.
I suppose this only works when Excel is selected as default application for the .xlsx extention.
I don't know about Mac OS, but if Windows Operating System is the case and provided the Microsoft Windows is properly installed, then consider using :
import os
os.system('start "excel" "C:\\path\\to\\myfile.xlsx"')
double-quotation is important for excel and C:\\path\\to\\myfile.xlsx ( where C just denotes the letter for the partition within the file system, might be replaced by D,E ..etc. ), and single-quotation is needed for the whole string within the os.system().
As in: How to open an Excel file with Python to display its content?
import os
file = "C:\\Documents\\file.xlsx"
os.startfile(file)
It opens the file with the default application.
If you want this to work with your most recent downloaded xlsx file, you can use the following:
import glob
import os
list_of_files = glob.glob('C:\\Downloads\\*.xlsx') *#note the .xlsx extension is needed to retrieve the last downloaded xlsx file.*
latest_file = max(list_of_files, key=os.path.getctime)
os.system(latest_file)
A minor improvement that handles spaces and explicitly uses Excel:
import os
file = "C:/Documents/file name with spaces.xlsx"
file_with_quotes = '"' + file + '"'
os.system('start "EXCEL.exe" {}'.format(file_with_quotes))

When saving excel file (openpyxl) and then trying to make excel open it on mac get `Permission denied` error

This code:
workbook.save(outputf)
system('open ' + outputf)
generates this error when run on my mac:
sh: /Users/tylerjw/Desktop/jim_data/August2013_report.xlsx: Permission denied
The file was created with openpyxl. I have not been able to reproduce the error outside of my application is a tkinter application that is writing a considerable amount of data to that file.
When I run similar code in windows it doesn't error, it opens excel with the file. The only difference is the absence of the open command.
What could case this error?
On my system (mac 10.6.8, python2.7.5, gcc 4.2.1) the following code works fine:
from openpyxl import Workbook
from os import system
wb = Workbook()
outputf = 'test.xlsx'
wb.save(outputf)
# see below *
system('open ' + outputf)
(see comments: I lost the bet. The error was somewhere else in the code and has nothing to do with system('open ' + whatever))
I bet there is something wrong with permissions in your new file on your system. Maybe you add
(docu)
st = os.stat(outputf)
os.chmod(outputf, st.st_mode | stat.stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
(with input from other link)
in the code instead of my commentary ('# see below *') Then it should be possible to open it by everyone and everything...
If it works, this is a workaround. There is a difference between our system and I do not know what difference. If not, well, I did not test it on my system (because I did not have a problem with the code), write a comment and I might play with the settings or maybe someone else has an idea.
Btw.: In a terminal in your folder: What output gives 'ls -l excelfilename' after execution of the python code? What programming environment do you use? I start the program via 'python2.7 pythonscript.py' in the terminal.

Categories

Resources