[英]How to copy a certain part of text from one file to another in python
要在此示例中提取文本的某个部分,我想从 d 提取到 f
input.txt 包含:
a
d
c
b
e
f
g
a
a
output.txt 应该包含从 d 到 f 但这个程序从 d 复制到 input.txt 文件的最后一行
f = open('input.txt')
f1 = open('output.txt', 'a')
intermediate_variable=False
for line in f:
if 'd' in line:
intermediate_variable=True
if intermediate_variable==True:
f1.write(line)
f1.close()
f.close()
我认为应该这样做:
contents = open('input.txt').read()
f1.write(contents[contents.index("d"):contents.index("f")])
有更方便的方式来读写文件,这个版本使用了一个生成器和'with'关键字(上下文管理器),它会自动为你关闭文件。 生成器(带有“yield”的函数很好,因为它们一次给你一行文件,尽管你必须将它们的 output 包装在 try/except 块中)
def reader(filename):
with open(filename, 'r') as fin:
for line in fin:
yield line
def writer(filename, data):
with open(filename, 'w') as fout: #change 'w' to 'a' to append ('w' overwrites)
fout.write(data)
if __name__ == "__main__":
a = reader("input.txt")
while True:
try:
temp = next(a)
if 'd' in temp:
#this version of above answer captures the 'f' as well
writer("output.txt", temp[temp.index('d'):temp.index('f') + 1])
except StopIteration:
break
直截了当:
### load all the data at once, fine for small files:
with open('input.txt', 'r') as f:
content = f.read().splitlines() ## use f.readlines() to have the newline chars included
### slice what you need from content:
selection = content[content.index("d"):content.index("f")]
## use content.index("f")+1 to include "f" in the output.
### write selection to output:
with open('output.txt', 'a') as f:
f.write('\n'.join(selection))
## or:
# for line in selection:
# f.write(line + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.