Openpyxl with python2.7 - python

I wanted to open excel file on python with using this code.
import openpyxl
wb= openpyxl.load_workbook('testfile.xlsx')
Error:No such file or directory: 'testfile.xlsx'
Where should I locate this file?
I am using Python2.7 on Spyder

Make sure that there is that file in the folder... Try this command to list the files in that folder just to make sure that python atleast recognizes or reads the files.
import os
print (os.listdir('your path'))
Try giving an absolute path. I mean give a leading slash which means an absolute path, or a path that starts at the root of your filesystem. No leading slash makes the path relative to your working directory.... I guess thats why it ain't working.
Lets say your file in downloads(as said in the comments)...
wb= openpyxl.load_workbook('/Users/name/Downloads/your_file')

Related

Code not able to locate file from within the same path as the program itself

My program is located under C:\Users\Username\pycode.py
My file to be called within the program is located under C:\Users\Username\<filename>
The file and the code are in the same directory.
When I call from within the program using the below set of codes,
import os; import sys
with open(os.path.join(sys.path[0], "file1.txt"), "r") as fn1:
print(fn1.read())
the Py code picks up the file and executes the applied methods on it.
However, when I don't use the above code and use as:
fn1 = open("file1.txt", "r")
print(fn1.read())
There is only an error that the file does not exist.
Any thoughts and ideas, what is missing to make the file within the local directory as the py code to recognize the file.
If it's relevant, I'm a beginner using VSCode on Windows 10.
Speaking from personal experience, it happens to me when I am using vscode and I am in a directory say d:/Desktop/python programs. But the file I want to open() is in the directory d:/Desktop/python programs/fun.
In this case it is not sufficient for me to use the path like "filename". Instead I need to use "/fun/filename". This is even though the file I am working on is in the fun folder.
So perhaps you could go to the terminal in VSCode (your IDE) and run cd "path to your file" and that should solve the problem
Try running the following code and see what output you get
import os
print(os.getcwd())
In my case this would print d:/Desktop/python programs

Setting working direction to direction of the script in Python (pyinstaller)

I have a pretty simple script that takes data from some .csv or .db files, performs manipulations and saves output in the similar files. I am working from Spyder with the parameter "Run in the directory of the file", so when I run the file my wd is set to file's directory automatically. SO that I put all files in one folder and do not mess with paths (e.g. using always open("data.csv")). And my files are stored like:
/Users/username/docs/script.py
/Users/username/docs/data.cv
/Users/username/docs/database.db
I've tried to use pyinstaller to that colleagues could you the script easily as well, but any time they would run it, it would set the working directory to /Users/username/ and all relative paths are getting broken.
How could I preserve this issue, so that the script (pyinstaller shell script) would be taking as working directory the folder with its location, like Spyder is doing?
Instead of using plain open('data.csv'), you should use a snippet like the following:
import os
import sys
if getattr(sys, 'frozen', False):
base_dir = sys._MEIPASS
else:
base_dir = os.path.abspath(os.path.dirname(__file__))
file = open(os.path.join(base_dir, 'data.csv'))
Then, when building you include your data files with --add-data=data.csv;.. Please use a colon (:) instead of a semi-colon (;) when not on Windows. If you're on Windows and using PowerShell, then escape the semi-colon with a backtick (`).
You can use the getcwd() function in os module to get the location of the current working directory. Then open the files like this.
open(os.getcwd()+'/data.csv')

python FileNotFoundError

I was writing a program that accesses a .txt file at the start of the program with the open() function. It ran without any errors on the IDE and I was also able to read the text file when running from the IDE without any issues. Although when I ran from the Python Launcher it threw a "FileNotFoundError"
Here's my code:
directions_object = open('warcards_directions.txt','r')
Further to Dan D's comment.. try putting this on the line in front of your open() call:
from os.path import abspath
print(abspath('warcards_directions.txt'))
You'll see that python looks in different places depending on where you run it from .. because it looks for files relative to the current working directory, which changes depending on how you run python.
This is a common problem for new comers. See here How to import files in python using sys.path.append? for some solutions (note the underlying problem in that post is the same as this one.. the fact that they're trying to import a file, and here we're trying to open one is not too important).
Also I'll add that I often reference things relative to the script itself... like this:
from os.path import abspath, join, dirname
script_dir = dirname(__file__)
txt_path = abspath(join(script_dir, "..", "path", "to", "warcards_directions.txt"))
This works if your txt file and your python script stay in the same place relative to each other (but might be installed in different places).
E.g. above assumes your script lives in C:\Foo\scripts\script.py and your text file lives in C:\Foo\path\to\warcards_directions.txt. The method above will work fine where ever you run the script from and it'll work if you move or rename the C:\Foo dir (e.g. to C:\Program Files\Bar). But it'll break if you decide to move scripts.py down a directory into C:\Foo (at which point you change the way txt_path is initialized to fix).
When you said "python launcher", do you mean the command line?
python myScript.py
If you, you will need to cd into the directory where the file is at before you can execute the script. Otherwise, provide the full path to the txt file in your script.

How do I find the exact location of a file in python with pygame?

I need to have the exact directory of an image for a game I'm making in python with pygame. I know what the folder and file are called, but not where my user puts it. Please help, I won't be able to continue my project without you guys :(
The file i'm trying to find is in the same folder as the .py and is a .bmp
If you know the path relative to where your python module is stored in the file system (as you seemed to indicate) you can use the following to calculate the abs path and then build up an appropriate path from there.
import os
print(os.path.abspath(__file__))
print(os.path.split(os.path.abspath(__file__)))
NOTE: Change print for python2.7
Use os.path.join to build up the new path.
Maybe have a look at the os.path documentation page, especially at os.path.abspath.

Opening/running Excel file from python

I need to start excel and open a file directly from python. Currently I am using:
import os
os.system('start excel.exe file.xls')
However I do not get desired result. I want to open a file from local destination (file is in the same folder with program), but this code open's the file with same name in my home (user) directory and not from my program directory.
The problem is that the directory where the program is located is not used. The current working directory is. So you have to find out which directory your program is located in, which python conveniently prepared for you in:
sys.path[0]
and either change directory to it:
os.chdir(sys.path[0])
or give full path for the file you want to open
os.system('start excel.exe "%s\\file.xls"' % (sys.path[0], ))
Note, that while Windows generally accept forward slash as directory separator, the command shell (cmd.exe) does not, so backslash has to be used here. start is Windows-specific, so it's not big problem to hardcode it here. More importantly note that Windows don't allow " in file-names, so the quoting here is actually going to work (quoting is needed, because the path is quite likely to contain space on Windows), but it's bad idea to quote like this in general!
You can also define the directory, where the python should operate.
import os
os.chdir('C:\\my_folder\\subfolder')
os.system('start excel.exe my_workbook.xlsx')
Don't forget to use backslashes in your path and there must be two of them everytime.
my_workbook.xlxs - here will be the name of your file
That file must be in that folder :)

Categories