问题:将多个文件文案合并到一个文件当中,并且输出这个文件。我用for循环加append语句却发现最后输出的文件里面,只有for所遍历的最后一个文件里面的文案。为什么会这样呢?
如下图,
out1.txt,out2.txt,out3.txt 里面的文案分别是:
out1.txt :我要测试一下1111
out2.txt :这是第二个测试
out3.txt : 3333
我希望 all_files里面有:out1.txt,out2.txt,out3.txt 的文案
但是输出结果只有out3.txt的内容。
以下是用来输出all_file(即含有所有文件文案的文件)的那部分代码
with open(path, 'r', -1, encoding='utf8') as txt:
test = txt.readlines()
names = os.path.split(path)
allfile_path = os.path.join(names[0], 'all_files')
with open(allfile_path, 'w', -1, encoding='utf8') as txt:
ss=[]
for s in test:
ss.append(s)
txt.writelines(s.strip('\n'))
你的本意是out1.txt,out2.txt,out3.txt 读出来的内容都放到test里,但是代码里test变量,每打开一个文件都重新赋值一次,所以最后只有最后一个文件的内容。test定义放到最外面,每读一个文件,test.extends(txt.readlines())
不知道你这个问题是否已经解决, 如果还没有解决的话:有帮助的话,请点采纳该答案~