My cwd is ~/Desktop/Development/Python/djcode/mysite, and I want to open a file on my Desktop. What is the syntax to open files in a different directory? (for example, if the file was in the cwd I would use open('file'). Thank you.
Try this:
>>> import os
>>> path = os.path.expanduser('~/Desktop/foo.txt')
>>> open(path, 'r')
<open file '/home/pat/Desktop/foo.txt', mode 'r' at 0x7f0455af0db0>
Use the path to it, either absolute:
myfile = open('/path/to/myfile.ext')
or relative:
myfile = open('../../../../myfile.ext')
depending on which is more appropriate for the situation. You can use os.path.expanduser() to expand the ~ portion of the path.
Use relative paths? ../../../../file
Use absolute path to the file, because if you move your program to another location or another computer, relative paths will break.
Use context manager while opening the file.
with open('c:\absolutepath\file') as f:
content = f.read()
Related
I recently made a small program (.py) that takes data from another file (.txt) in the same folder.
Python file path: "C:\Users\User\Desktop\Folder\pythonfile.py"
Text file path: "C:\Users\User\Desktop\Folder\textfile.txt"
So I wrote: with open(r'C:\Users\User\Desktop\Folder\textfile.txt', encoding='utf8') as file
And it works, but now I want to replace this path with a relative path (because every time I move the folder I must change the path in the program) and I don't know how... or if it is possible...
I hope you can suggest something... (I would like it to be simple and I also forgot to say that I have windows 11)
Using os, you can do something like
import os
directory = os.path.dirname(__file__)
myFile = with open(os.path.join(directory, 'textfile.txt'), encoding='utf8') as file
If you pass a relative folder to the open function it will search for it in the loacl directory:
with open('textfile.txt', encoding='utf8') as f:
pass
This unfortunately will only work if you launch your script form its folder. If you want to be more generic and you want it to work regardless of which folder you run from you can do it as well. You can get the path for the python file being launched via the __file__ build-in variable. The pathlib module then provides some helpfull functions to get the parent directory. Putting it all together you could do:
from pathlib import Path
with open(Path(__file__).parent / 'textfile.txt', encoding='utf8') as f:
pass
import os
directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(directory, 'textfile.txt')
with open(file_path, encoding='utf8') as file:
# and then the code here
I'm trying to open all csv files within a given folder and then "perform a calculation". I'm currently trying to use glob but it doesn't see any files in the folder. All the code after this seems to work with a single file path but I imagine im using glob wrong.
path = "C:/build/Files*.csv"
for fileName in glob.glob(path):
with open(fileName, 'r') as file, \
open('C:PycharmProjects/Result.csv', 'r') as result_file:
#perform caluclation
I'm not sure what your file path looks like, but perhaps are you missing a /?
path = "C:/build/Files/*.csv" seems like a file structure that would be more likely.
Either make the path a raw string:
path = r"C:/build/Files*.csv"
or use double backslash:
path = "C:\\build\\Files*.csv"
I´m trying to save a file, which I create with the "open" function.
Well I tried nearly everything to change the directory, but nothing works. The file gets always saved in the folder of my file, which I read in before.
file = open(fname[0] + ft, 'w')
file.write("Test")
file.close()
So this is it simple, but what do I have to add, to change the path of creation?
The File Dialog in a individual Function:
global fname
fname = QFileDialog.getOpenFileName(None, 'Please choose your File.',"C:\\Program Files", "Text-Files(*.txt)")
And the File Typ ( in a individual Function too) I set the file type by ticking a check box and ft will set to .py or .pyw
if self.exec_py.isChecked() == True:
global ft
ft = ".py"
I should have mentioned that I already tried os.path.join and os.chdir, but the file will get printed in the file anyway. Any solutions or approaches how to fix it? Here is how i tried it:
tmppath = "C:/temp"
tmp = os.path.join(tmppath,fname[0]+ft)
file = open(tmp, 'w')
Your question is a little short on details, but I am guessing that fname is the tuple returned by QFileDialog, and so fname[0] is the absolute path of the original file. So if you display fname[0], you will see something like this:
>>> fname[0]
'C:\\myfolder\\file.txt'
Now look what happens when you try to use that with os.path.join:
>>> tmppath = 'C:\\temp'
>>> os.path.join(tmppath, fname[0])
'C:\\myfolder\\file.txt'
Nothing! Conclusion: attempting to join two absolute paths will simply return the original path unchanged. What you need to do instead is take the basename of the original path, and join it to the folder where you want to save it:
>>> basename = os.path.basename(fname[0])
>>> basename
'file.txt'
>>> os.path.join(tmppath, basename)
'C:\\tmp\\file.txt'
Now you can use this new path to save your file in the right place.
You need to provide the full filepath
with open(r'C:\entire\path\to\file.txt', 'w') as f:
f.write('test')
If you just provide a file name without a path, it will use the current working directory, which isn't necessarily the directory where the python script your running is located. It will be the directory where you launched the script from.
C:\Users\admin> python C:\path\to\my_script.py
In this instance, the current working directory is C:\Users\admin, not C:\path\to.
I'm trying to load the json file but it gives me an error saying No such file or directory:
with open ('folder1/sub1/sub2/sub2/sub3/file.json') as f:
data = json.load(f)
print data
The above file main.py is kept outside the folder1. All of this is kept under project folder.
So, the directory structure is Project/folder1/sub1/sub2/sub2/sub3/file.json
Where am I going wrong?
I prefer to point pathes starting from file directory
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'relative/path/to/file.json')
with open(file_path, 'r') as fi:
pass
this allows not to care about working directory changes. And also this allows to run script from any directory using it's full path.
python script/inner/script.py
or
python script.py
I would use os.path.join method to form the complete path starting from the current directory.
Something like:
json_filepath = os.path.join('.', 'folder1', 'sub1', 'sub2', 'sub3', 'file.json')
As always, an initial slash indicates that the path starts from the root. Omit the initial slash to indicate that it is a relative path.
In python I´m creating a file doing:
f = open("test.py", "a")
where is the file created? How can I create a file on a specific path?
f = open("C:\Test.py", "a")
returns error.
The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:
"C:\\Test"
or
r"C:\Test"
I recommend using the os module to avoid trouble in cross-platform. (windows,linux,mac)
Cause if the directory doesn't exists, it will return an exception.
import os
filepath = os.path.join('c:/your/full/path', 'filename')
if not os.path.exists('c:/your/full/path'):
os.makedirs('c:/your/full/path')
f = open(filepath, "a")
If this will be a function for a system or something, you can improve it by adding try/except for error control.
where is the file created?
In the application's current working directory. You can use os.getcwd to check it, and os.chdir to change it.
Opening file in the root directory probably fails due to lack of privileges.
It will be created once you close the file (with or without writing). Use os.path.join() to create your path eg
filepath = os.path.join("c:\\","test.py")
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py
f = open("test.py", "a") Will be created in whatever directory the python file is run from.
I'm not sure about the other error...I don't work in windows.
The besty practice is to use '/' and a so called 'raw string' to define file path in Python.
path = r"C:/Test.py"
However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.
Use os module
filename = "random.txt"
x = os.path.join("path", "filename")
with open(x, "w") as file:
file.write("Your Text")
file.close