import os import csv # 设置要遍历的目录 source_directory = 'config' target_directory = 'csv_output' # 确保目标目录存在 os.makedirs(target_directory, exist_ok=True) # 遍历源目录及其子目录 for root, dirs, files in os.walk(source_directory): for file in files: if file.endswith('.txt'): source_file_path = os.path.join(root, file) target_file_name = os.path.splitext(file)[0] + '.csv' target_file_path = os.path.join(target_directory, target_file_name) # 读取TXT文件并写入CSV文件 try: with open(source_file_path, 'r', encoding='utf-8') as txt_file, open(target_file_path, 'w', newline='', encoding='utf-8') as csv_file: txt_reader = csv.reader(txt_file, delimiter='\t') csv_writer = csv.writer(csv_file) # 跳过第一行 next(txt_reader, None) for row in txt_reader: # 去掉每行的第一列 csv_writer.writerow(row[1:]) except Exception as e: print(f"Failed to convert: {source_file_path} to {target_file_path}") print(e)