【问题标题】:Concatenate or Append Multiple Files in Numerical Order to New File with Python使用 Python 以数字顺序将多个文件连接或附加到新文件
【发布时间】:2021-02-09 20:36:11
【问题描述】:

首先我会说我已经看到了类似question 的答案。我试图用它来解决我的问题,但我无法让它正常工作。

我有多个具有相同前缀和后缀的 .xyz 文件,从 0 开始。可能有 100 多个文件,因此不要单独定义它们是必不可少的。我需要按数字顺序将这些文件合并/连接/附加到merged.xyz。例如:

输出0.xyz:

H 1.0 1.0 1.0

输出1.xyz:

H 2.0 2.0 2.0

合并的.xyz:

H 1.0 1.0 1.0
H 2.0 2.0 2.0

我已经将其作为一个简单的测试用例进行了尝试:

tempfiles = ['output0.xyz', 'output1.xyz']

f = open("bigtextfile.xyz", "w")
for tempfile in tempfiles:
    f.write(tempfile.read())

但我明白了:

Traceback (most recent call last):
  File "Test.py", line 28, in <module>
    f.write(tempfile.read())
AttributeError: 'str' object has no attribute 'read'

我尝试过的另一种选择:

prefix = "output"
suffix = ".xyz"

count = 0
while count <= 1:
    for filename in os.listdir('./'):
        if filename.endswith(suffix):

            xyzFile = open(prefix + str(count) + suffix, "r")
            lines = xyzFile.readlines()
            xyzFile.close()

            merged = open("merged" + suffix, "a")
            for line in lines:
                merged.write(line)
            merged.close()
    count += 1

但它会复制第一个文件两次,第二个文件复制三次:

H 1.0 1.0 1.0
H 1.0 1.0 1.0
H 2.0 2.0 2.0
H 2.0 2.0 2.0
H 2.0 2.0 2.0

你建议我如何前进?我倾向于第二种解决方案,因为它已经按数字顺序自动获取文件的内容。如果您需要任何其他详细信息以及如何改进问题,请告诉我。

【问题讨论】:

    标签: python


    【解决方案1】:

    你有:

    tempfiles = ['output0.xyz', 'output1.xyz']
    
    f = open("bigtextfile.xyz", "w")
    for tempfile in tempfiles:
        f.write(tempfile.read())
    

    但是循环中的tempfile 被分配了一个文件的名称,例如'output0.xyz',并且作为一个字符串它没有read 的方法;您需要将其用作open 的参数:

    tempfiles = ['output0.xyz', 'output1.xyz']
    
    with open("bigtextfile.xyz", "w") as f:
        for tempfile in tempfiles:
            with open(tempfile) as infile:
                f.write(infile.read())
    

    请注意,我使用的是with 上下文管理器,它会在它们管理的块终止时自动关闭文件。

    更新

    此代码将尝试处理文件 ouput0.xyz, output1.xyz, ... 并将终止,直到出现打开错误。它不会显式读取目录,而是假设文件是​​连续编号 0、1、2 ... N:

    from itertools import count
    
    
    with open("bigtextfile.xyz", "w") as f:
        for suffix in count(0): # suffix takes on values 0, 1, 2, ...
            try:
                with open(f'output{suffix}.xyz') as infile:
                    f.write(infile.read())
            except Exception:
                break # get out of loop when we can no longer open outputN.xyz for some value N
    

    【讨论】:

    • 啊,是的,这很有意义。
    • 对自动按数字顺序读取文件有什么建议吗?
    • 哦,聪明。非常感谢!
    【解决方案2】:
    tempfiles = ['output0.xyz', 'output1.xyz']
    
    with open("bigtextfile.xyz", "w") as f:
        for tempfile in tempfiles:
            with open(tempfile, 'r') as temp:
                f.write(temp.read())
        
    

    【讨论】:

    • 这和我的回答有什么不同?
    • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
    猜你喜欢
    • 2011-07-27
    • 2021-12-26
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-13
    • 2020-02-24
    • 2020-11-01
    相关资源
    最近更新 更多