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

Question:

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?

Asked By: KishuInu

||

Answers:

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)

Answered By: Alarm-1202

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

Answered By: turnt_alienn

after messing with mine for about 2 hours, I finally just completely deleted the text file, created another one, saved it as a .txt under a different name and then tried the basic open(test.txt) and it worked.

Answered By: Wadeofearth
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.