Python合并多个TXT文件为单个文件的实现问题求助
多TXT文件合并优化
首先确保导入依赖模块:
import glob import numpy as np
你原有的二进制读写代码本身可以实现多文件合并,如果你运行后只得到单个文件内容,大概率是glob匹配路径异常,可先打印匹配结果验证:
path = "/home/Documents/Python/" read_files = glob.glob(path + "*.txt") # 打印匹配到的文件列表,确认是否识别到所有待合并txt print(read_files)
如果是纯文本文件,推荐改用文本模式读写,指定编码避免乱码,同时加换行符避免不同文件首尾内容拼接:
with open("contents.txt", "w", encoding="utf-8") as outfile: for f in read_files: with open(f, "r", encoding="utf-8") as infile: outfile.write(infile.read() + "\n")
含注释行的数值读取解决方案
报错原因是代码尝试将#开头的注释行直接转换为float,只需在读取时过滤注释行和空行即可:
with open("contents.txt", "r", encoding="utf-8") as f: x = np.array([ float(raw.strip()) for raw in f.readlines() if raw.strip() and not raw.strip().startswith("#") ])
如果你的数值是多列用空格/逗号分隔的,可修改转换逻辑适配对应格式。
内容的提问来源于stack exchange,提问作者vdu16
相关产品推荐
相关产品推荐

