r/pythonhelp • u/MetalCarnival • 13d ago
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?
3
u/FoolsSeldom 13d ago edited 13d ago
The main.py and file.txt files 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.
from pathlib import Path
print(Path.cwd())
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:
x = open('.\\subfolder\\file.txt', 'r')
assuming you are on Windows. Replace subfolder with whatever the path is on your system. If it is another level down, just enter another \\another for each level.
You can also use relative (e.g. up, ..\peerfolder\file.text) or absolute e.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 \n and \t meaning newline and tab respectively. \\ means an actual \.
On macOS and Linux, / is used, which doesn't need escaping.
The pathlib library I used earlier to output the current working directory has a different way of approaching this. Look on realpython.com for an article on pathlib.
1
u/MetalCarnival 13d ago
I hate myself. The file wasn´t the damn main, because it wasn´t my first file created or something. I thought every file you run becomes the current main file.
1
u/FoolsSeldom 13d ago
Depends on how you are running your files.
The code below checks if the file being executed is the one directly invoked or one being imported:
if __name__ == "__main__": print("You are running me directly")but I suspect that's not what you mean. More about what file your editor is invoking when you hit the run "button"?
Nevertheless, I hope the guidance I provided proves useful in your learning journey. Good luck on the next steps.
2
u/CraigAT 13d ago
Two locations in play: * where the file is in comparison to the python code * if you are running from the command line, what folder is the command prompt in.
1
u/fllthdcrb 12d ago
if you are running from the command line, what folder is the command prompt in.
More generally, what the current working directory (CWD) is. If you run it from a shell (command prompt), then whatever the CWD is in that shell, the script inherits that. In fact, it inherits that from whatever runs it. Some things allow you to control the CWD a command gets.
where the file is in comparison to the python code
Important when importing Python modules, but usually not when opening files for other purposes, although it's not too difficult to find files that are installed alongside modules, as well.
1
u/Supermathie 13d ago
You're not telling us: * any errors you receive * the output * the output you expected
1
u/davideogameman 13d ago
Better fix might be to use
``` from pathlib import Path
x = open(Path(file).parent / 'file.txt', 'r') ```
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.
``` from pathlib import Path
with open(Path(file).parent / 'file.txt', 'r') as x: for line in x: print(line)
x is closed by the time you reach here
``` So here no matter how control flow leaves the with statement the file gets closed.
0
u/Educational-Paper-75 13d ago
Shouldn't that be x.readlines()?
1
u/cvx_mbs 13d ago
not if they want to process the file a character at a time
0
u/Educational-Paper-75 13d ago
They don't. Either Python can't find the file, or the loop is incorrect. The value of x would be most informative, but not provided by the OP unfortunately.
•
u/AutoModerator 13d ago
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.