1

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)

Shoof
  • 11
  • 1
  • 1
    Your code works for me. Are you sure the file is in the same folder as your script? Have you saved you txt file? Do you have a small example of the contents? – Loocid Nov 03 '22 at 00:10
  • Most probably you are not opening the file you mean you are opening and the file which you actually opening has no text. So make sure you are opening the right file and you will see its text content as output. – Claudio Nov 03 '22 at 00:13

2 Answers2

0

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.

paaoogh
  • 1
  • 2
  • I tried this but now instead of printing an empty space it just prints [] – Shoof Nov 03 '22 at 00:42
  • Does your file actually contain something? Try with print(os.stat("test.txt").st_size) form the os library – paaoogh Nov 03 '22 at 00:44
  • It returns 0. but when opening the file I see there is stuff written. – Shoof Nov 03 '22 at 00:50
  • 2
    It's extremely likely that you're opening a different file with the same name in a different folder. – Blckknght Nov 03 '22 at 01:25
  • Actually I just fixed it, VS Code wasn't making the changes to the txt file. But when I opened it with notepad and wrote text it worked. So I just reinstalled VS Code and my problem was solved – Shoof Nov 03 '22 at 01:58
-2

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)
  • 2
    No, it is not better. Opening using `with open()` is the better way of dealing with file operations in Python. – Claudio Nov 03 '22 at 00:20
  • I tried this, however it did not work. I tried many different ways to printing the .txt file, but all of them end up printing an empty space. – Shoof Nov 03 '22 at 00:36