我正在遍历文件,我需要在匹配特定字符串时在行上方插入一个文本块。请帮忙!
convBlockMoved = False
for line in outfile:
if(line.startswith('mappingSchemeAxis') and not convBlockMoved):
for convLine in conversionBlocks:
print convLine, #Print this above line
convBlockMoved = True
注意:conversionBlocks是一个String数组
答案 0 :(得分:1)
不是Python的答案,但sed
可以在一行中完成。
文件:
$ cat > so.txt
foo
bar
baz
qux
在第baz
行之前插入:
$ sed -i '/baz/i11\n22\n33' so.txt
结果:
$ cat so.txt
foo
bar
11
22
33
baz
qux
答案 1 :(得分:0)
试试这个:
def replace_import_in_f(f_in, pattern, plus):
with open(f_in) as f:
in_str = f.read()
in_str = re.sub(pattern, pattern + plus + "\n", in_str)
with open(f_in, "w") as f:
f.write(in_str)
模式必须是您在上面添加新行的整行。
注意:由于整个文件内容的f.write(),这对于中等文件是完美的。 (使用python 3.4测试)
[UPDATE]
更复杂但是要处理大文件,使用coroutine在行处理期间写入临时文件。如果没有错误,请替换临时文件。
import tempfile, os
def write_file(pattern="", plus=""):
with tempfile.NamedTemporaryFile(delete=False) as fin:
yield fin
while True:
line = (yield)
if pattern:
if line.startswith(pattern):
fin.write(bytes(plus, 'UTF-8'))
fin.write(bytes(line, 'UTF-8'))
def copy_file(path_in, path_out):
with open(path_in) as fin, open(path_out, "w") as fout:
for line in fin:
fout.write(line)
def read_and_file(fname, pattern="", plus=""):
try:
with open(fname) as fh:
# generator creation
gen_write = write_file(pattern, plus)
# get the tempfile
fout = next(gen_write)
for line in fh:
# send line
gen_write.send(line)
except (IOError, OSError) as e:
print(e)
else:
fout.close()
if os.name == "nt":
copy_file(fout.name, fname)
else:
os.rename(fout.name, fname)
答案 2 :(得分:0)
因此,如果您的文件不是很大,您可以一次读取所有行,然后使用列表。使用列表的插入方法的示例是:
def main():
lines = []
with open('input.txt') as f:
lines = f.readlines()
ins_at = find_occurences_of('mappingSchemeAxis', lines)
for i in ins_at:
lines.insert(i,'HELLO WORLD\n')
with open('input.txt', 'w') as f:
f.writelines(lines)
def find_occurences_of(needle, haystack):
ret = []
for i, line in enumerate(haystack):
if line.startswith(needle):
ret.append(i)
return ret
if __name__ == '__main__':
main()
答案 3 :(得分:0)
基本上,您正在读取字符串列表,并且您希望在某些条件下将新的列表元素放在当前字符串之上。
我建议你(如果文件不是太大)是将输入中的行附加到输出列表,在每行匹配条件之前附加所需的文本。类似于以下内容
for line in infile.readlines ():
if line.startswith ('mappingSchemeAxis'):
outcontent.append ('xxxxx')
outcontent.append (line)
for line in outcontent:
print (line) # here you want to write the content to the output file
我发布的有点晚了:D