首页 > 解决方案 > 命名所有连接的 txt 文件

问题描述

我想将所有 .txt 文件中的数据收集到一个文件中,并在此连接文件中添加收集到的 .txt 名称的名称。我尝试用我的代码来实现它,但没有。如果您能提供帮助,我将不胜感激

资源:

import glob

read_files = glob.glob("*.txt") # find all .txt files and then goes read
fileName = 'NoName' 
with open("result.txt", "wb") as outfile: # create output file named result.txt
    for f in read_files:
        fileName = f
        with open(f, "rb") as infile:
            outfile.write(str(fileName) + '\n' + infile.read()) # in this line i try to add at top off collected text 'Name' of collected .txt, but i got some errors ¯\_(ツ)_/¯

标签: python-3.xfileparsingcopy

解决方案


尝试使用.decode("utf-8")并更改wbw

前任:

import glob

read_files = glob.glob("*.txt") # find all .txt files and then goes read 
with open(filename, "w") as outfile: # create output file named result.txt
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(f + '\n' + infile.read().decode("utf-8") )

推荐阅读