简体   繁体   English

将 txt 文件中的特定行复制到一个新的 txt 文件中

[英]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

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

相关问题 Python 如何在一个 file.txt 中写入 5 行,在一个新的 file1.txt 中写入另外 3 行,例如 +=1 - Python How to write 5 lines in one file.txt and the other 3 lines in a new file1.txt with +=1 for example 将 .txt 文件的特定行(包含大量行)写入新的 txt 文件 - Write specific lines of a .txt file ( containing large no of lines) to a new txt files 使用文件中的新行创建.TXT文件 - Creating a .TXT file with new lines within the file 如何将一行从.txt文件复制到经过修改的新.txt文件中 - How to copy a line from a .txt file into a new .txt file with modifications 如何读取.txt文件的特定行? - How to read specific lines of .txt file? 打印特定行的txt文件python - Printing specific lines txt file python 加载文件,.txt文件中的特定行进入数组 - Loadfile, specific lines from .txt file into array 用python在新行上将文本写入txt文件? - Writing text to txt file in python on new lines? 如何使用 %BASH 将包含特定字符串的行从 a.csv 文件复制到 Python 中的 a.txt 文件? - How do you copy lines that contain specific strings from a .csv file to a .txt file in Python using %BASH? Python,比较2个txt文件,找到第2个txt文件中唯一的行和output到一个新的txt文件 - Python, compare 2 txt files, find unique lines in the 2nd txt file and output to a new txt file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM