0

I have a code using which i am getting count from file

Cases:

1. ignore blank lines
2. ignore empty lines 
3. ignore spaces
4. ignore tabs 

The code works fine it gives proper count

sum(1 for i in open('/path/ABC.txt',"r").readlines() if i.strip())

Their is no close given in code , Does once it is open the python automatically closes the file ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Does this answer your question? [Is close() necessary when using iterator on a Python file object](https://stackoverflow.com/questions/1832528/is-close-necessary-when-using-iterator-on-a-python-file-object) – rzlvmp Aug 19 '21 at 05:49
  • 1
    Enable warnings with: `import warnings; warnings.simplefilter('default')` - Python will tell you if you missed closing a file. – Piotr Praszmo Aug 19 '21 at 06:10
  • @PiotrPraszmo : Thanks by importing warnings it showed me : `ResourceWarning : unclosed file` –  Aug 19 '21 at 06:19

3 Answers3

1

No, the file will not be closed in this case.

See the example below

f.closed - Returns True if file is closed else False

# Your case
f1 = open('text.txt', 'r')
sum(1 for i in f1.readlines() if i.strip())
print(f1.closed)

# Using Context Manager
f2 = open('text.txt', 'r')
with f2:
    sum(1 for i in f2.readlines() if i.strip())
print(f2.closed)
False
True

You can see that in the first case, the file is NOT closed where as in the second case, it is closed. So always use a context manager when reading & writing files.

From the Docs

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.

Ram
  • 4,724
  • 2
  • 14
  • 22
0

At the end of your script all handlers will be closed. It doesn't matter for a read-only file. This can become hazardous for files opened for writing. The proper way is to use the context manager because at the end of the scope, the file will be properly closed.

with open('/path/ABC.txt',"r") as fp:
    sum(1 for i in fp.readlines() if i.strip())
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

Python automatically gets rid of the file during the garbage collection or at the end of the program which means you don't have to close it.

But I would use the "with" keyword where gives a better syntax and exceptions handling as well as closes the file at the end of it.

with open('/path/ABC.txt',"r") as f: 
    #The rest of the code