[英]Copy specific lines in txt file into one new txt file
I'm working with the python.我正在使用 python。
I have 1.txt file:我有 1.txt 文件:
Data = 10,
Time taken = 2s,
Architecture = Microcontroller,
Speed = 1s,
Device = STC12C,
I want to copy only into new txt file:我只想复制到新的 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]
If you print new_text you get:如果你打印 new_text 你会得到:
>>>
Architecture = Microcontroller,
Device = STC12C,
Which is what we want.这就是我们想要的。 Now you save it into a new file.
现在将其保存到一个新文件中。
# 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
you won't need to close the files, as mentioned by @ 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.