文本文件(.txt文件)与python中的列表的串联? [英] Concatenation of Text Files (.txt files) with list in python?
本文介绍了文本文件(.txt文件)与python中的列表的串联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个文本文件1.txt和2.txt
Suppose I am having two text files 1.txt and 2.txt
1.txt
的内容为:
['Hi', 'I', 'am']
和
2.txt
的内容为:
['a', 'boy']
如何以相同的方式高效地将它们连接起来并将其写入新文件,例如3.txt
,它应该如下所示:
How to join the same and write the same into a new file in time efficient manner, say 3.txt
, which should look like this:
['Hi', 'I', 'am', 'a', 'boy']
我尝试过:
import os
file_list = os.listdir("path")
with open('out.txt', 'a+') as outfile:
for fname in file_list:
with open(fname) as infile:
outfile.write(infile.read())
推荐答案
您可以尝试以下方法:
inputText = []
for file in ['1.txt','2.txt']:
with open(file,'r') as file:
inputText.extend(file.readlines()+['\n'])
with open ('3.txt','w') as output:
for line in inputText:
output.write(line)
或
with open ('3.txt','w') as output:
for file in ['1.txt','2.txt']:
with open(file,'r') as file:
for line in file:
output.write(line)
output.write('\n')
编辑为您的评论:
import re
inputList = []
for file in ['1.txt','2.txt']:
with open(file,'r') as infile:
for line in infile:
inputList.extend(re.sub('[^A-Za-z0-9,]+', '', line).split(","))
print(inputList)
with open('3.txt','w') as outfile:
for line in inputList:
outfile.write(line + '\n')
这篇关于文本文件(.txt文件)与python中的列表的串联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文