简体   繁体   English

使用fileinput.input将行插入文件

[英]Insert a line into a file using fileinput.input

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. 我想知道为什么这行不通,所以建议您解决任何建议。

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. 第一个问题,将file更改为其他名称, file是python中的保留名称。

And, make sure you're passing a list of filenames if you were trying to pass multiple files. 并且,如果要传递多个文件,请确保传递文件名list

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):
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM