Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newby question: Opening files not working #137

Closed
GrigorijSchleifer opened this issue Feb 22, 2023 · 3 comments
Closed

Newby question: Opening files not working #137

GrigorijSchleifer opened this issue Feb 22, 2023 · 3 comments

Comments

@GrigorijSchleifer
Copy link

Holle community, first of all thank you holzschu for making such a powerful app. Really great work.

I am new to programming and when attempting to open a simple *.txt file to loop over it for a book exercise I get a FileNotFoundError. I am sure I am missing something trivial.

[~/Documents/testdir]$ python open_file.py 
Traceback (most recent call last):
  File "/private/var/mobile/Containers/Data/Application/B7C98837-9423-45A4-A7E8-E17E40DF01AB/Documents/test
dir/open_file.py", line 1, in <module>
    with open("~/Documents/testdir/test_text.txt") as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '~/Documents/testdir/test_text.txt'

When I type pwd I get:

[~/Documents/testdir]$ pwd
~/Documents/testdir

And listing the contents of the directory shows the files I am working on:

[~/Documents/testdir]$ ls
open_file.py    test_text.txt

My python code in open_file.py is:

with open("~/Documents/testdir/test_text.txt") as f:
    f = f.readlines()
    for ln in f:
        print(ln)

Where is the recommendet path to store all my files? And again, thank you for your hard work.

Greetings from Bonn

Grigorij

@holzschu
Copy link
Owner

holzschu commented Feb 22, 2023

Python sends the argument of "open" directly to the "open()" function, without any pre-treatment. "open()" is a low level function, it does not check anything in the file name. So the function tries to open a file named, litterally, ~/Documents/testdir/test_text.txt and finds that it doesn't exist. You need to first expand the ~ to its full value, using os.path.expanduser("~/Documents/testdir/test_text.txt").

Alternatively, you can replace "~" with os.environ["HOME"], as in: open(os.environ["HOME"] + "/Documents/testdir/test_text.txt").

You could also use a local file path, rather than an absolute file path: open("test_text.txt").

@GrigorijSchleifer
Copy link
Author

Dear holzshu thank you very much. It dead work.

@GrigorijSchleifer
Copy link
Author

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants