r/learnpython • • Jan 08 '23
*urgent ish*
I don’t have a scoobie what’s wrong here, been coding a couple months (not a crazy am tho as have been away) And completing free conde camp p4e course, and gunna move on to other after
And I’m tryna get this thing open but aprently it’s not in the dorectory Wich I think it is…. Please.. need help
Thanks (Excuse my shyte spelling)
(Using vs code) - on the left it says (where my file is)
EX.07-01 ex_07-01.py Workfile.txt
I’m tryna get work file to open
My code is just
F = open(‘workfile.txt’) For line in f: Print(f)
Thnx
0
Upvotes
View all comments
Show parent comment
2
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Jan 08 '23
Very well.
From your question, it was clear that wherever VS Code was looking and where the text file was were different. Most likely your code and the file were in a subfolder. When Python attempted to read the file, it failed because by default Python looks for files in the current working directory - wherever VS Code's PowerShell terminal was - and couldn't find it from there.
My first solution would have involved changing the current working directory to point to wherever your script and the text file were.
With this solution, which I prefer, you don't need to worry about the current working directory at all. If you can construct an absolute path to your script, you can then proceed to getting any paths you care about relative to that, meaning you don't need to give two hoots where they are in practice.
pathlibmakes this very easy, and__file__gives you the path to the current script. In my example I just took the parent directory and then added the name of the text file to get a full path to that.And voilà; now it should always find the text file.
As for if you need to do this every time, that depends, but I'd say yes. It's not as bad as it sounds, though.