在Python文件中的当前行上方写一行
我在一个文件中循环,当它与特定字符串匹配时,我需要在一行上方插入一个文本块。请帮忙在Python文件中的当前行上方写一行,python,readline,Python,Readline,我在一个文件中循环,当它与特定字符串匹配时,我需要在一行上方插入一个文本块。请帮忙 convBlockMoved = False for line in outfile: if(line.startswith('mappingSchemeAxis') and not convBlockMoved): for convLine in conversionBlocks: print convLine, #Print this above line
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是字符串数组请尝试以下操作:
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进行测试)
[更新]
更复杂的是,为了处理大文件,在行处理过程中使用协程写入临时文件。如果没有错误,请替换临时文件
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)
不是Python的答案,但可以在一行中完成
文件:
$ 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
因此,如果您的文件不是很大,您可以一次读取所有行,然后处理列表。使用列表插入方法的示例如下:
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()
基本上,您正在读取一个字符串列表,并且在某些条件下,您希望在当前列表元素之上放置一个新的列表元素
我建议您(如果文件不是太大)将输入中的行附加到输出列表中,在与您的条件匹配的每行之前附加您想要的文本。类似于下面的内容
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所以你想修改文件?或者打印它?如果遇到MemoryError、IOError或OSError异常,这将非常失败。一种更惯用的方法是写入临时文件,只有在写入完成且没有错误时才调用操作系统。重命名(temp_file,f_in)
(但不在Windows中)。只需更新我的答案:)