1
for line in fileinput.FileInput("file.txt", inplace=1):
  if "success" in line:
    print(line)

When I use fileinput, the file 'file.txt' is not released. I could see the issue 'file.txt' still in use. When I do the above function using normal file operation , no issue is shown

How to fix the issue with fileinput.

I used the below code snippet , but the issue is showing again . The file is not getting closed I guess

f = fileinput.input("file.txt", inplace=1)
    for line in f:
      if "success" in line:
      print(line)
    f.close()

1 Answer 1

1

In Python 2.7, you have to explicitly call close() on the fileinput instance:

try:
  f = fileinput.input("file.txt", inplace=1)
    for line in f:
      if "success" in line:
        print line, end=""
else:
  f.close()

Since Python 3.2, the FileInput class can be used as a context manager. See the fileinput documentation for more information.

with fileinput.input(files=('file.txt'), inplace=1) as f:
  for line in f:
    if "success" in line:
      print(line)
Sign up to request clarification or add additional context in comments.

10 Comments

Note that fileinput is meant to be used with multiple files; when iterating over lines in a single file, you might as well use with file.open('file.txt') as f: ... f.readlines() ....
@Marjin - Yeah , I Know that. I need to understand what is the issue here. Why fileinput throws such an issue.
Thanks Marjin. The issue got resolved. My python version is 2.7 .
I updated my Python 2.7 answer (see above); you should be good once you explicitly close the FileInput instance.
Glad I could help. If my answer helped you, please use the check mark next to the answer to show others that your problem was solved. Welcome to StackOverflow!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.