簡體   English   中英

將 txt 文件中的特定行復制到一個新的 txt 文件中

[英]Copy specific lines in txt file into one new txt file

我正在使用 python。

我有 1.txt 文件:

Data = 10,
Time taken = 2s,
Architecture = Microcontroller,
Speed = 1s,
Device = STC12C,

我只想復制到新的 txt 文件中:

Architecture = Microcontroller,
Device = STC12C,
# filepath is the path of the file you are reading
# for example filepath = r"C:\Users\joe\folder\txt_file.txt"
f = open(filepath, "r")
Lines=f.readlines() #here you have a list of all the lines
new_text = Lines[2] + Lines[4]

如果你打印 new_text 你會得到:

>>> 
Architecture = Microcontroller,
Device = STC12C,

這就是我們想要的。 現在將其保存到一個新文件中。


# filepath if the path of the file you want to create 
# for example filepath = r"C:\Users\joe\folder\new_txt_file.txt"
text_file = open(newfilepath, "w")
 
#write string to file
text_file.write(new_text)
 
#close file
text_file.close()

f.close() # I forgot to close the first file

編輯:如@CrazyChucky所述,通過使用with open你不需要關閉文件。

with open(filepath, 'r') as f:
    Lines=f.readlines()
new_text = Lines[2] + Lines[4]

with open(newfilepath, 'w') as f:
    f.write(new_text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM