Python – How to change/choose the file path in Python

pythonpython-3.x

I'm trying to access a .txt file in Python and I can't figure out how to open the file. I ended up copying the contents into a list directly but I would like to know how to open a file for the future.

If I run this nothing prints. I think it's because Python is looking in the wrong folder/directory but I don't know how to change file paths.

sourcefile = open("CompletedDirectory.txt").read()
print(sourcefile)

Best Answer

The file CompletedDirectory.txt is probably empty.

If Python could not find the file, you would get a FileNotFoundError exception:

>>> sourcefile = open("CompletedDirectory.txt").read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'CompletedDirectory.txt'

Note that using read() in this way is not recommended. You're not closing the file properly. Use a context manager:

with open("CompletedDirectory.txt") as infile:
    sourcefile = infile.read()

This will automatically close infile on leaving the with block.