0

I want to insert a line into the middle of a text file that I have.

I have tried:

for line in fileinput.input('file.txt', inplace=1):
    if line.startswith('example'):
        print 'input line'

which worked. But I wanted this to loop over many files, so I changed it to:

for line in fileinput.input('{0}' .format(file), inplace=1):
    if line.startswith('example'):
        print 'input line'

and I get the error message:

Traceback (most recent call last):
  File "addline.py", line 8, in <module>
    for line in fileinput.input('{0}' .format(file), inplace=1):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/fileinput.py", line 253, in next
    line = self.readline()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/fileinput.py", line 322, in readline
    os.rename(self._filename, self._backupfilename)
OSError: [Errno 2] No such file or directory

I would like to know why this doesn't work and any suggestions to fix would be appreciated.

3
  • your problem seems to be file doesn't exist, which the error shows. what is file? is that a filename or a directory? Commented Nov 9, 2014 at 23:15
  • It's a file in a folder. But when I change {0} for the actual filename it works. I thought there must be a problem using {0} with fileinput.input. I'll check everything again. Commented Nov 9, 2014 at 23:24
  • 1
    The problem is file is a reserved name in Python, try using another name like f, and you should be fine Commented Nov 9, 2014 at 23:28

1 Answer 1

2

The problem seems to be in this line:

for line in fileinput.input('{0}' .format(file), inplace=1):

change to this:

# f is the filename
for line in fileinput.input('{0}'.format(f), inplace=1):

First problem, change file to other name, file is a reserved name in python.

And, make sure you're passing a list of filenames if you were trying to pass multiple files.

Try changing to this:

...
files = ['file1', 'file2', ...] # put your files in a list first
# and pass the list of files to .input
for line in fileinput.input(files, inplace=1):
...
Sign up to request clarification or add additional context in comments.

3 Comments

@user1551817, that's fine and I'm glad it helps :)
How is '{0}'.format(string) ever going to be different from just string? Or maybe str(thing) if the thing you were passing to format was not already a string.
@tripleee, well you're right its kind of redundant in this case, but the issue OP had just wasn't about string formatting, it's more about the file didn't exist in the first place. But yeah, your point is valid.

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.