Home > Blockchain >  Can't read text file in VS code (Python)
Can't read text file in VS code (Python)

Time:10-21

So I have this Python code in VS Code:

s = open("name.txt")
print("Your name is", s)

I have the text file "name.txt" in the same folder as the program I'm running. This text file just contain the text "Johnny".

When running the file, I first got the error message:

FileNotFoundError: [Errno 2] No such file or directory: 'name.txt'

But after some Googling, I turned on the setting "Execute In File Dir":

Setting for opening file

But now, I instead get this nonsene output:

Your name is <_io.TextIOWrapper name='name.txt' mode='r' encoding='cp1252'>

But it should have been:

Your name is Johnny

Does anybody have an idea where it goes wrong?

CodePudding user response:

You need to read the file, at the moment your output to the s variable is an object. To read the file out to a string all you need to include is either:

s = open("name.txt", "r").read() or s = open("name.txt", "r").readlines()

(The "r" refers to that you're only reading the file, which is usually implicit but it's good to include it for readability)

CodePudding user response:

You have to assign the read function to the variable instead of open s = read(name.txt)

  • Related