Python脚本求助:提取多CFD输出CSV末行并写入新CSV
Hey there! Sounds like you're so close to wrapping up your CFD CSV processing script—nice work getting to the point where you can print the correct content to the terminal. Let's knock out that last step of automatically writing everything to a new file, no manual copy-paste needed.
Here's a complete, commented script that does exactly what you need, with extra safeguards for CSV formatting and edge cases like empty files:
import os import csv # ---------------------- # 配置参数(根据你的情况修改) # ---------------------- # 存放CFD CSV文件的目录路径(比如和脚本同目录就用 "./") csv_directory = "./cfd_simulation_results" # 输出文件的名称(会自动创建/覆盖) output_filename = "cfd_last_rows_combined.csv" # 打开输出文件,准备写入(用with语句自动管理文件关闭) with open(output_filename, "w", newline="", encoding="utf-8") as output_file: # 使用CSV写入器确保字段格式正确(比如带引号的内容不会乱) csv_writer = csv.writer(output_file) # 遍历目标目录下的所有文件 for file_name in os.listdir(csv_directory): # 只处理CSV文件,跳过其他类型 if file_name.lower().endswith(".csv"): # 拼接完整的文件路径,避免找不到文件 full_file_path = os.path.join(csv_directory, file_name) # 打开当前CSV文件读取内容 with open(full_file_path, "r", encoding="utf-8") as input_file: # 读取所有行(如果你的CSV特别大,看下面的优化方案) csv_reader = csv.reader(input_file) all_rows = list(csv_reader) # 确保文件不是空的,避免报错 if all_rows: # 取最后一行 last_row = all_rows[-1] # 在最后一行的最前面插入文件名 last_row.insert(0, file_name) # 写入到输出文件 csv_writer.writerow(last_row) # 保留你之前的终端打印功能 print(f"Processed: {file_name} | Last row added to output") print(f"\nDone! All last rows saved to {output_filename}")
关键细节解释(适合Python新手):
with语句:自动帮你打开和关闭文件,不用手动写close(),避免资源泄漏csv.reader/writer:专门处理CSV格式,比如如果你的数据里有逗号或者引号,它会自动处理成合法的CSV格式,比直接读文本行更可靠- 空文件检查:
if all_rows确保不会因为某个空CSV文件导致脚本崩溃 - 文件名过滤:
file_name.lower().endswith(".csv")会匹配.CSV和.csv两种后缀,更灵活
针对超大CSV文件的优化:
如果你的CFD CSV文件特别大(几百MB/GB),读取所有行到内存里会很卡,可以换成这种逐行读取的方式,只保留最后一行:
# 替换上面的读取部分 with open(full_file_path, "r", encoding="utf-8") as input_file: csv_reader = csv.reader(input_file) last_row = None # 逐行遍历,每次更新last_row为当前行,最后就得到最后一行 for row in csv_reader: last_row = row if last_row is not None: last_row.insert(0, file_name) csv_writer.writerow(last_row)
小提示:
- 把
csv_directory改成你实际存放CSV文件的路径,比如如果CSV和脚本在同一个文件夹,就设为"./" - 如果你的CSV文件用的是中文编码(比如GBK),把
encoding="utf-8"改成encoding="gbk" - 如果需要把完整文件路径(而不是只文件名)加到行开头,把
file_name换成full_file_path就行
内容的提问来源于stack exchange,提问作者tLashbrooke
相关产品推荐
相关产品推荐

