Home > Software engineering >  .txt file is opening but prints nothing
.txt file is opening but prints nothing

Time:11-03

I'm trying to open a text file and print it as a string. I've made sure there is text in the .txt file but when I run the code it just prints an empty space, I don't know what to do at this point since I couldn't find anything that could help me with my problem.

with open('test.txt', 'r') as file:
    data = file.read().rstrip()

print(data)

CodePudding user response:

When things aren't opening check the following:

  • You wrote exactly the same in your code as the one you saved. "file.txt" is not the same as "File.txt" for Python (same goes for accents and special characters).
  • The file you are trying to read is in the same directory. If your code is at users/bla/documents/another_folder and you just pass the name of the file to your code, then the file must be at users/bla/documents/another_folder too. If not, be shure to add it into the string path as "path/to/your/file/file.txt"
  • Make sure that the extension .txt is the same as your file.
  • If you checked that but everything seems correct, try:
with open(path_to_file) as f:
    contents = f.readlines()

And see if "contents" has something.

CodePudding user response:

I think it is better if you use open("file.txt","r") function to do it. So your code will be like this:

file=open("test.txt","r")
data=file.read().strip()
print(data)
  • Related