1

So I'm trying to create a method that can search files and print them out.

def search():
    searched = input("... ")
    with open(searched + ".py", "r") as my_file:
        print(my_file)
search()

but the console prints out <_io.TextIOWrapper name='RandomPrac.py' mode='r' encoding='UTF-8'> What does this mean?

2 Answers2

3

you print my_file variable, which is of type _io.TextIOWrapper. What you actually need is

print(my_file.read())
Ali Yılmaz
  • 1,657
  • 1
  • 11
  • 28
3

As Ali Yilmaz's answer already nicely explains, you're printing the file object, not the contents of that file.

For smallish files, just read() the file to get the contents as a string, and print that, as in his answer. And, since you're searching for *.py files, you almost certainly do have smallish files.

But if the file might be gigantic, it's probably better to loop over it and print each line as you read it:

for line in my_file:
    print(line, end='')

Or, if you want to be more concise but possibly too clever:

print(*my_file, sep='')
abarnert
  • 354,177
  • 51
  • 601
  • 671