python - 如何将文本文件(或 .con 文件)连接成一个文件?

标签 python

我在将多个文件连接成一个文件时遇到问题。当我尝试做这个文件时,它起作用了。但是,对于两个文件,它不会创建合并两个文件的新文件。我尝试了 glob.globos.path.join 中的所有内容,但是我不断收到语法或列表属性没有对象替换的相同错误。

import glob
import os
import os.path

read_files_2=['NYASv1.con', '20Rev1.con','Nv1.con',
              'L1v1.con','fig_L1v1.con','R_L1v1.con']

read_files = glob.glob("I:\T\FE19\Cont\Traes\ctg\Sing\%s.con",% read_files_2)

with open("result.con", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())

我收到 %s.con",% read_files_2 的语法错误

最佳答案

  1. 如果所有文件都位于同一文件夹中,只需使用 path.join 迭代它们即可:
import os

dr = "I:\T\FE19\Cont\Traes\ctg\Sing"
read_files = [os.path.join(dr, f) for f in read_files_2]

其余代码与您的相同

  • 如果不是,请使用最顶层目录(包括所有目录)并使用 os.walk :
  • import os
    
    dr = "I:\T\FE19\Cont\Traes\ctg\Sing"
    read_files = []
    for root, _, files in os.walk(dr):
        for file in files:
            if file in read_files_2:
                read_files.append(os.path.join(root, file))
    

    如果您仍然想使用glob,您可以使用iglob,它是迭代器版本:

    import glob
    
    dr = "I:\T\FE19\Cont\Traes\ctg\Sing\**\*.con"
    read_files = []
    for file in glob.iglob(dr, recursive=True):
        if file in read_files_2:
            read_files.append(file)
    

    关于python - 如何将文本文件(或 .con 文件)连接成一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937052/

    相关文章:

    Python tkinter,使两个文本小部件的滚动同步

    python - 使用对象检测时出现 Open cv 错误

    Python 实现广度优先搜索

    python - 未包装的标签仍然存在

    python - 二维数组每一列的外积形成一个三维数组 - NumPy

    python - 使用Beautiful soup分析python中的表

    Python - 分割整个文本文件

    python - 传递多个参数返回 'Response' (python)

    python - python-mysql-connector 1.16、django 1.6 和 python 3.2.3 导入错误

    python - 分块读取文件 - RAM 使用,从二进制文件中读取字符串