1

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?

KishuInu
  • 61
  • 7

2 Answers2

2

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)

Alarm-1202
  • 78
  • 2
  • 10
  • Thank you so much! It worked now. Can you please explain what the "r" part of the code means? I think I understand the rest. – KishuInu Oct 21 '21 at 10:32
  • I added an end note about the "r", in your code it's not really necessary because it's the default setting for `open()` but it's good because other people can then see that you're intending only to read the file rather than write to it. – Alarm-1202 Oct 21 '21 at 10:35
0

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