I have this basic python script to print out the contents of an entire book I have saved as a text file:
f = open("pride.txt", "r", encoding="UTF-8")
s = f.read()
f.close()
print("Contents of file:", s)
But every time I run it, it doesn’t actually print out the contents of the book, the output is just:
Contents of file:
What am I doing wrong? I made sure that there is no typo and I am absolutely positive that the text file is saved under the same directory as my program.
>Solution :
Your code looks okay, so to eliminate the possibility that the active directory of the script is not the same as the script’sactual location, give the full path to the file.
Also, it’s safer to open files like this:
path = "/full/path/to/the/file/pride.txt"
with open(path, "rt", encoding="UTF-8") as f:
s = f.read()
print("Contents of file:", s)