如何使用Python合并目录下AA_前缀文件并转换日期格式输出
Python实现方案
以下提供两种可直接运行的实现方案:
方案1:pandas实现(推荐,代码简洁适合大量文件场景)
首先安装依赖:pip install pandas
import glob import pandas as pd # 匹配所有AA_前缀的txt文件,如需指定目录替换路径即可 file_list = glob.glob("./AA_*.txt") all_data = [] for file in file_list: # 读取文件,自动处理字段间多余空格 df = pd.read_csv(file, skipinitialspace=True, dtype=str) # 拼接为要求的日期格式 df["date"] = df["year"] + "-" + df["month"] + "-" + df["day"] + ":" + df["hour"] # 仅保留需要的两列 df = df[["date", "price"]] all_data.append(df) # 合并所有文件数据 merged_df = pd.concat(all_data, ignore_index=True) # 输出结果,缺失值保持为NA,不输出索引 merged_df.to_csv("merged.txt", index=False, na_rep="NA")
方案2:纯Python标准库实现(无需安装额外依赖)
适合轻量场景,不需要第三方库支持:
import glob # 匹配所有目标文件,如需指定目录替换路径即可 file_list = glob.glob("./AA_*.txt") output_rows = [["date", "price"]] for file in file_list: with open(file, "r", encoding="utf-8") as f: lines = f.readlines() # 跳过每个文件的表头行,从第二行开始读取数据 for line in lines[1:]: line = line.strip() # 跳过空行 if not line: continue # 拆分字段并去除多余空格 year, month, day, hour, price = [item.strip() for item in line.split(",")] # 拼接为要求的日期格式 date = f"{year}-{month}-{day}:{hour}" output_rows.append([date, price]) # 写入结果文件,可调整空格数匹配对齐需求 with open("merged.txt", "w", encoding="utf-8") as f: for row in output_rows: f.write(f"{row[0]:<16}{row[1]}\n")
内容的提问来源于stack exchange,提问作者user3104352
相关产品推荐
相关产品推荐

