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')
添加回答
舉報