[Tutor] reading files in Python 3
Zachary Ware
zachary.ware+pytut at gmail.com
Thu Mar 30 16:47:45 EDT 2017
On Mar 30, 2017 15:07, "Rafael Knuth" <rafael.knuth at gmail.com> 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 ...
"The above does not work" is not descriptive. How does it not work? Is
there a traceback? Does the program stop responding? Does the computer
catch fire?
In this case, the problem is the bogus Unicode escape that you
inadvertently included in your path: `\Us...`. To fix it, either use a
'raw' string (`r"C:\Users\..."`) or use forward slashes rather than
backslashes, which Windows is happy to accept.
Regards,
--
Zach
(On a phone)
More information about the Tutor
mailing list