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.
filedoesn't exist, which the error shows. what isfile? is that a filename or a directory?fileis a reserved name in Python, try using another name like f, and you should be fine