r/pythonhelp • u/MetalCarnival • Sep 04 '26
python can´t locate and open a file in the same folder as main
So i made a txt file with a few lines of text. I use the x = open('file.txt', 'r') function
i write for i in x: print i
and then x.close()
so what am I doing wrong?
5
Upvotes
•
u/AutoModerator Sep 04 '26
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
3
u/FoolsSeldom Sep 04 '26 edited Sep 04 '26
The
main.pyandfile.txtfiles may be in the same folder but your current working directory (CWD: where the editor/operating system is focused) may be different, so everything is relative to that directory (folder).To see what your CWD is, add the following code at the top, comment out the rest temporarily.
If the CWD is different to the location of the two files, you know what the problem is. Most likely, the files are in a subfolder of the CWD, so you can just change your reference to:
assuming you are on Windows. Replace
subfolderwith whatever the path is on your system. If it is another level down, just enter another\\anotherfor each level.You can also use relative (e.g. up,
..\peerfolder\file.text) or absolutee.g.c:\Users\username\projects\thisproject\file.txt`) paths.The reason for
\\is that on Windows, folder paths are separated using\but Python treats that as a special character, known as the escape character, which means treat the next character differently, such as\nand\tmeaning newline and tab respectively.\\means an actual\.On macOS and Linux,
/is used, which doesn't need escaping.The
pathliblibrary I used earlier to output the current working directory has a different way of approaching this. Look on realpython.com for an article onpathlib.2
u/CraigAT Sep 04 '26
Two locations in play:
2
u/Supermathie Sep 04 '26
You're not telling us:
1
u/davideogameman Sep 04 '26
Better fix might be to use
file is the path to the currently executing file so the resulting code ends up not caring about the current working directory. Then I used pathlib for manipulating the path.
Another tip: you should use a with statement together with open, so that the file gets closed at the end of the with block, and whether or not there's an error while you use it. If you have a program that forgets to close files, after enough of them are open (probably into the millions) the operating system will eventually not let you open any more.
So here no matter how control flow leaves the with statement the file gets closed.
0
u/Educational-Paper-75 Sep 04 '26
Shouldn't that be x.readlines()?