亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在python中將文本的某一部分從一個文件復制到另一個文件

如何在python中將文本的某一部分從一個文件復制到另一個文件

至尊寶的傳說 2022-06-07 19:18:18
要在此示例中提取文本的某個部分,我想從 d 提取到 finput.txt 包含:adcbefgaaoutput.txt 應該包含從 d 到 f 但這個程序從 d 復制到 input.txt 文件的最后一行f = open('input.txt')f1 = open('output.txt', 'a')intermediate_variable=Falsefor line in f:    if 'd' in line:        intermediate_variable=True        if intermediate_variable==True:            f1.write(line)f1.close()f.close()
查看完整描述

3 回答

?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

我認為應該這樣做:


contents = open('input.txt').read()

f1.write(contents[contents.index("d"):contents.index("f")])


查看完整回答
反對 回復 2022-06-07
?
慕俠2389804

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


查看完整回答
反對 回復 2022-06-07
?
米脂

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')


查看完整回答
反對 回復 2022-06-07
  • 3 回答
  • 0 關注
  • 457 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號