Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why isn't my Python script printing the contents of my file?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading