python 文件串联和组合文件

标签 python string concatenation

我的主要问题是:

我有一组文件,我在 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/

相关文章:

python - 在 numpy 中正确执行以下操作的正确方法

python - Pandas 在连接字符串时合并结果丢失的行

python - 根据字典替换字符串的快速方法

python - 有没有办法使用 String replace() 方法来替换任何东西

MySql,结合变量做变量名?

python - 在 webhook 中解析 JSON

Python Panda read_excel - 用户输入部分 io 名称

python - 如何按数据框的值进行分组?

python - pandas concat 生成 nan 值

postgresql - 在 Postgresql 中创建生成的列时出错