[Tutor] reading files in Python 3

Mats Wichmann mats at wichmann.us
Thu Mar 30 16:45:39 EDT 2017

On 03/30/2017 11:02 AM, Rafael Knuth wrote:
> I can read files like this (relative path):
> with open("Testfile_B.txt") as file_object:
>     contents = file_object.read()
>     print(contents)
> But how do I read files if I want to specify the location (absolute path):
> file_path = "C:\Users\Rafael\Testfile.txt"
> with open(file_path) as file_object:
>     contents = file_object.read()
>     print(contents)
> The above does not work ...

Yeah, fun.  You need to escape the \ that the idiot MS-DOS people chose
for the file path separator. Because \ is treated as an escape character.

Get familiar with the path function in the os module, it will let you do
examinations of file paths, by the way, including constructing them in ways


simple workaround: use a r letter in front of the string (r for raw):

file_path = r"C:\Users\Rafael\Testfile.txt"

ugly workaround: escape the backslashes so they aren't treated specially:

file_path = "C:\\Users\\Rafael\\Testfile.txt"

you can use os.path.join() to build up a path string in a more
independent way, although it doesn't work quite as expected. To get what
you're asking for, though:

file_path = os.path.join(os.path.expanduser('~Rafael'), 'Testfile.txt')

More information about the Tutor mailing list