简体   繁体   中英

Copy specific lines in txt file into one new txt file

I'm working with the python.

I have 1.txt file:

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

I want to copy only into new txt file:

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:

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

Edit: By using with open you won't need to close the files, as mentioned by @ 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM