在文件夹-Python中每两个连续的txt文件合并一次 导入全局 导入操作系统 filenames=glob.glob('*.txt')#目录中所有.txt文件的列表 将open('outfile.txt','w')作为f: 对于文件名中的文件: 将打开(文件)作为内嵌: filename=os.path.splitext(文件)[0] f、 写入(“+”infle.read()+”+文件名)

在文件夹-Python中每两个连续的txt文件合并一次 导入全局 导入操作系统 filenames=glob.glob('*.txt')#目录中所有.txt文件的列表 将open('outfile.txt','w')作为f: 对于文件名中的文件: 将打开(文件)作为内嵌: filename=os.path.splitext(文件)[0] f、 写入(“+”infle.read()+”+文件名),python,merge,Python,Merge,我找到了这个脚本,用于合并文件夹中的每个txt,但我不知道如何访问文件名列表中的下一个文件。我已经合并了文件,但由于我为每一行添加了符号,所以我拒绝合并该文件,而是尝试在以前合并 编辑:例如 我有File1.txt,File2.txt,File3.txt,。。。我想要文件1=File1+File2,File2=File3+File4 import glob import os filenames = glob.glob('*.txt') # list of all .txt files in

我找到了这个脚本,用于合并文件夹中的每个txt,但我不知道如何访问文件名列表中的下一个文件。我已经合并了文件,但由于我为每一行添加了符号,所以我拒绝合并该文件,而是尝试在以前合并

编辑:例如

我有File1.txt,File2.txt,File3.txt,。。。我想要文件1=File1+File2,File2=File3+File4

import glob
import os
filenames = glob.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            filename = os.path.splitext(file)[0]
            f.write("<s>+"infile.read()+"</s>"+filename)
你可以做:

filenames = ['file1.txt', 'file2.txt', 'file3.txt', 'file4.txt']
您将获得:

for f1, f2 in zip(filenames[0:-1:2], filenames[1::2]):
    print(f1, f2)
    # do your operations here

但是,如果文件数量为奇数,则无法访问最后一个文件

您的问题不是很清楚。如果你想跳过一个文件,你能在循环中使用continue吗?
# iteration 1
file1.txt file2.txt
# iteration 2
file3.txt file4.txt