3 回答
TA贡献1828条经验 获得超4个赞
我认为应该这样做:
contents = open('input.txt').read()
f1.write(contents[contents.index("d"):contents.index("f")])
TA贡献1719条经验 获得超6个赞
有更方便的方式来读写文件,这个版本使用了一个生成器和'with'关键字(上下文管理器),它会自动为你关闭文件。生成器(带有 'yield' 的函数很好,因为它们一次给你一行文件,尽管你必须将它们的输出包装在 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
TA贡献1836条经验 获得超3个赞
直截了当:
### 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')
添加回答
举报