CSV合并函数运行后出现随机空行的问题求助
问题解决:合并CSV时出现多余空白行
问题原因
空白行是因为从文件读取的每一行本身已包含换行符(\n或\r\n),但代码中又额外拼接了一个\n,导致每行前多了一个换行,最终出现多余空白行。此外原代码还存在文件路径拼接不严谨、未自动关闭文件的问题。
修复方案
下面是两种修复方式,你可以根据需求选择:
方式1:手动处理换行符(轻量修改)
import os def combine_csvs(csv_header, ends_with, directory): csv_list = [] for item in os.listdir(directory): item_path = os.path.join(directory, item) if os.path.isfile(item_path) and item.endswith(ends_with): csv_list.append(item_path) # 可选:按文件名排序,保证合并顺序符合预期 csv_list.sort() csv_merge = csv_header for file_path in csv_list: # 使用with语句自动关闭文件,更安全 with open(file_path, 'r') as csv_in: for line in csv_in: # 去除行尾的换行符(兼容Windows/Unix) stripped_line = line.rstrip('\r\n') if stripped_line == csv_header: continue # 跳过空行(如果文件中存在) if stripped_line: csv_merge += '\n' + stripped_line return csv_merge
方式2:使用csv模块(更专业可靠)
如果需要处理复杂CSV场景(比如字段包含逗号、引号),推荐用Python内置的csv模块,避免手动处理的潜在问题:
import os import csv def combine_csvs(csv_header, ends_with, directory): csv_list = [] for item in os.listdir(directory): item_path = os.path.join(directory, item) if os.path.isfile(item_path) and item.endswith(ends_with): csv_list.append(item_path) csv_list.sort() # 初始化结果列表,先加入表头 header_row = csv_header.split(',') result_rows = [header_row] for file_path in csv_list: with open(file_path, 'r') as f: reader = csv.reader(f) next(reader) # 跳过文件自身的表头 for row in reader: if row: # 跳过空行 result_rows.append(row) # 将结果行转换为CSV格式字符串 return '\n'.join([','.join(row) for row in result_rows])
测试结果
执行print(combine_csvs("name,lowest,highest", "_final.csv", ".")),会得到无空白行的正确输出:
name,lowest,highest John,14,53 Adam,13,60 Mary,9,34
内容的提问来源于stack exchange,提问作者Dolphin
相关产品推荐
相关产品推荐

