0

Let's say I have the following code that is trying to print out some files from a list and using a single loop variable to loop through each file. After each iteration of the outer loop, I lose reference to the opened file I just printed out. Um.. I am wondeirng how bad this code really is... I couldn't think of any other harms it will do besides taking a few counts if the system defines a maximum number of opened files...etc.

file_names = ["a.txt","b.txt","c.txt"]
for file_name in file_names:
    file = open(file_name)
    for line in file:
        print(line)
    print("\n\n\n")
user3463521
  • 572
  • 2
  • 7
  • 16

1 Answers1

0

You can read about adverse effects here: Is explicitly closing files important?

It will probably work in most cases, until it doesn't ;)

To avoid any problems related to unclosed file references, you should use with open(file_name) as file: as documented here: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

pktl2k
  • 598
  • 5
  • 12