我的主要问题是:
我有一组文件,我在 python 中以这种方式连接它们:
sys.stdout=open("out.dat","w")
filenames = ['bla.txt', 'bla.txt', 'bla.txt']
with open('out.dat', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
with open('out.dat') as f:
print "".join(line.strip() for line in f)
sys.stdout.close()
bla.txt 文件看起来像
aaa
目的是让它看起来像
aaaaaaaaa
(同一个字符串3次,不是每次都换行...)
出于某种原因,我所做的会产生如下所示的输出
aaaaaa
a
我不确定为什么会发生这种情况,以及是否有更简单/更优雅的解决方案。
第二个问题是,最终,我的计划是拥有许多不同的文件(例如字母三元组),我可以将它们连接成所有可能的组合:aaabbbccc、aaacccbbb、...等
任何指导表示赞赏!谢谢!
最佳答案
您的代码有一些令人困惑的地方,我将在相应的地方留下一些评论:
# Not sure what is reason for this
sys.stdout=open("out.dat","w")
filenames = ['bla.txt', 'bla.txt', 'bla.txt']
# This does what you need
with open('out.dat', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
# Here, you open `out.dat` and rewrites it content back into it -
# because you made `sys.stdout = open("out.dat", "w")` above.
# All these lines could be removed (along with `sys.stdout` assignment above)
with open('out.dat') as f:
print "".join(line.strip() for line in f)
sys.stdout.close()
我能想到的最简约的方法:
# Open output
with open('out.dat', 'w') as outfile:
# Iterate over each input
for infilename in ['bla.txt'] * 3:
# Open each input and write it to output
with open(infilename) as infile:
outfile.write(infile.read())
至于你的错误,应该不会发生,你能确认bla.txt
的内容正是aaa
吗?
关于python 文件串联和组合文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171953/