[英]How to read multiple .txt files in a folder and write into a single file using python?
I am trying to read files with.txt extension and wanted to append into a single txt file.我正在尝试读取扩展名为 .txt 的文件,并希望将 append 转换为单个 txt 文件。 I could read data.
我可以读取数据。 But what is the best way to write into single.txt file?
但是写入 single.txt 文件的最佳方法是什么?
Try this.尝试这个。
x.txt: x.txt:
Python is fun
y.txt: y.txt:
Hello World. Welcome to my code.
z.txt: z.txt:
I know that python is popular.
Main Python file:主要 Python 文件:
list_=['x.txt','y.txt','z.txt']
new_list_=[]
for i in list_:
x=open(i,"r")
re=x.read()
new_list_.append(re)
with open('all.txt',"w") as file:
for line in new_list_:
file.write(line+"\n")
sources = ["list of paths to files you want to write from"]
dest = open("file.txt", "a")
for src in sources:
source = open(src, "r")
data = source.readlines()
for d in data:
dest.write(d)
source.close()
dest.close()
If your destination doesnt already exist you can use "w"(write) mode instead of "a"(append) mode.如果您的目的地不存在,您可以使用“w”(写入)模式而不是“a”(附加)模式。
After you find the filenames, if you have a lot of files you should avoid string concatenation when merging file contents because in python string concatenation comes with O(n) runtime cost.找到文件名后,如果您有很多文件,则在合并文件内容时应避免字符串连接,因为在 python 中,字符串连接会带来 O(n) 运行时成本。 I think the code below demonstrates the full example.
我认为下面的代码演示了完整的示例。
import glob
# get every txt files from the current directory
txt_files = glob.iglob('./*.txt')
def get_file_content(filename):
content = ''
with open(filename, 'r') as f:
content = f.read()
return content
contents = []
for txt_file in txt_files:
contents.append(get_file_content(txt_file))
with open('complete_content.txt', 'w') as f:
f.write(''.join(contents))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.