首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将txt文件中的特定行复制到一个新的txt文件中。

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

Stack Overflow用户
提问于 2022-03-01 13:00:18
回答 1查看 130关注 0票数 -2

我在和蟒蛇一起工作。

我有一个.txt文件:

代码语言:javascript
复制
Data = 10,
Time taken = 2s,
Architecture = Microcontroller,
Speed = 1s,
Device = STC12C,

我只想复制到新的txt文件中:

代码语言:javascript
复制
Architecture = Microcontroller,
Device = STC12C,
EN

回答 1

Stack Overflow用户

发布于 2022-03-01 13:17:10

代码语言:javascript
复制
# 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,你会得到:

代码语言:javascript
复制
>>> 
Architecture = Microcontroller,
Device = STC12C,

这就是我们想要的。现在将其保存到一个新文件中。

代码语言:javascript
复制
# 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所提到的那样关闭文件。

代码语言:javascript
复制
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)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71308879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档