我在和蟒蛇一起工作。
我有一个.txt文件:
Data = 10,
Time taken = 2s,
Architecture = Microcontroller,
Speed = 1s,
Device = STC12C,我只想复制到新的txt文件中:
Architecture = Microcontroller,
Device = STC12C,发布于 2022-03-01 13:17:10
# 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,您不需要像@CrazyChucky所提到的那样关闭文件。
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)https://stackoverflow.com/questions/71308879
复制相似问题