![](/img/trans.png)
[英]Python How to write 5 lines in one file.txt and the other 3 lines in a new file1.txt with +=1 for example
[英]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
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.