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.
Related
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
I have a script called "test.py" and refers to a config file called "cfg.yaml". These two reside in the same directory called "test/scripts".
test/scripts/test.py
test/script/cfg.yaml
Now I am writing a bash script inside "test/data1/data2" called task.sh
From inside of task.sh, I want to make a call to the python script
test.sh contents are as below:
#!/bin/sh
python ../../scripts/test.py
test.py opens and reads the cfg.yaml like open("cfg.yaml") but when the test.sh is called, it fails because "cfg.yaml" is NOT referred with relative path. How do I resolve this?
try
#!/bin/sh
cd ../../scripts
python test.py
I assume in test.py you are referencing the yaml with a local path that expects the script to be running from the scripts directory (not from data1/data2)
as an aside you can always print os.getcwd() to see what your working directory is while running the python script (or just pwd in bash)
If you want to refer to a file in terms of its relative location to the script, you can't just use a relative path for that, because the script may not be in the current working directory. In fact, in your case, it's guaranteed not to be in the current working directory.
The usual quick&dirty solution is to get the script path explicitly:
import os
import sys
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
That sys.argv[0] is the full name of your script—which on most platforms means either an absolute path, or a relative path that's at least still valid at this point. If you're worried about those other platforms, you may want to look at __file__. Of course if you're running the script out of a zipfile or similar, neither one will be useful.
open(os.path.join(scriptdir, "cfg.yaml"))
(Or you can even forcibly os.chdir(scriptdir) if you want, but that can be a bad idea if you're, e.g., accepting pathnames from the user.)
The right solution is to write your script and data files to be installed (even if you don't actually install anything and run it out of the source tree), and then use pkg_resources to find the data files. That will also solve a whole lot of other problems for you—but it does require a bit more learning first. See the Python Packaging User Guide if you want to get started on that road, and Package Data and Data Files as particular starting points.
Not a major issue but just an annoyance I've come upon while doing class work. I have my Notepad++ set up to run Python code straight from Notepad++ but I've noticed when trying to access files I have to use the full path to the file even given the source text file is in the same folder as the Python program being run.
However, when running my Python program through cmd I can just type in the specific file name sans the entire path.
Does anyone have a short answer as to why this might be or maybe how to reconfigure Notepad++?
Thanks in advance.
The problem is that your code is assuming that the current working directory is the same as the script directory. This is not true in general. Of course it is true if you're in a cmd window, and you cd to the script directory before running it.
If you don't want to rely on that (e.g., because you want to be able to run scripts from Notepad++, or directly from Explorer), what you want to do is use the script directory explicitly. For example:
import os
import sys
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
with open(os.path.join(scriptdir, 'myfile.txt')) as f:
# etc.
If you have a ton of files that your scripts reference in a ton of places, it might be better to explicitly set the working directory. Just add one line:
os.chdir(scriptdir)
For anything beyond quick&dirty scripts, it's usually better to build an installable package and use pkg_resources to access the data files. Read the Tutorial on Packaging and Distributing Projects for more details. But as long as you're only hacking up scripts to help you maintain your specific system, the scriptdir solution is workable.
In the properties of the shortcut that you use to start Notepad++, you can change its working directory, to whichever directory you're more accustomed to starting from in Python. You can also begin your python program with the appropriate os.chdir() command.
I made a simple python script which creates a text file. The contents of the script are
f = open("New", "w")
f.close
Now I moved the script to the desktop (I'm on a mac) and ran it, and nothing shows up. No file is created on the desktop that is visible for me.
I actually made this little script because one of my other scripts involves opening/creating a text file and reading from it. I entered the information wrong while in my program forever, and now the entire thing is broken and I cant fix it because I have no idea where it's created the darn text file. I was under the impression that just opening a file with giving it an absolute path would create it in the same directory as the script. I seem to have been mistaken.
I've been launching the script from the terminal with the command
python3 /Users/me/Desktop/script.py
Because of that, I feel like its creating the file somewhere in the python3 install location or within wherever the python3 unix exec is located. I think. Can't check.
Are any of you guys willing to help out?
-pipsqueaker117
EDIT: Here's a link to the big program which broke.
It'll be created in the current working directory, which is the directory from which you called the script.
Your file will be created in the current directory (most probably in /Users/me/ if you just opened the terminal)
Try:
cd /Users/me/Desktop/
python3 /Users/me/Desktop/script.py
You should modify your program to change the working directory (before you write the file) to the place where you want files to show up.
import os
os.chdir('/Users/me/Desktop') # or whatever
This should be a directory where you have permission to write files.
You can always ask:
import os
cwd=os.getcwd()
print(cwd)
That will print the directory the file (without a path) will be opened in.
You can change to a specific directory (in Python) this way:
import os
try:
os.chdir('/Users/me/Desktop')
except OSError as e:
print e
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 :)