0

I am aware that when you open a file in Python, you must always close it. However, I was wondering what happens if you're not assigning your file to a variable and are only opening it in a print function.

Example: print(open('file.txt','r').read())

Is there a way to close a file opened within a function?

Something more pythonic than

F=open('file.txt','r')
print(F.read())
F.close()
Oleg Silkin
  • 508
  • 1
  • 5
  • 12

2 Answers2

2

Use the with construct.

with open('file.txt', 'r') as f:
    print(f.read())

If the file is very large, I suggest iterating over it and printing it a line at a time:

with open('file.txt', 'r') as f:
    for line in f:
        print(line, end='')

Of course, if the file is that large, it's probably not useful to print it to an ordinary console, but this practice is very useful for processing large files.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

So opening a file like that is not a good idea.

Just use context managers:

with open('file.txt','r') as f:
    print(f.read())
bcollins
  • 3,379
  • 4
  • 19
  • 35