You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中删除CSV表头后,如何正确读取同程序修改的文件?

解决CSV文件删除表头后仍读取到表头的问题

方法一:等待shell命令执行完成

你的问题核心是调用Popen后未等待命令执行完毕就立即读取文件,此时文件还未被修改,所以仍读到原表头。可以改用subprocess.run()(Python3.5+),它会自动等待命令执行完成:

import subprocess

# 替换原Popen代码
cmd = f"tail -n +2 {cleaned_file_sorted_on_ts}.csv > tmp.csv && mv tmp.csv {cleaned_file_sorted_on_ts}.csv"
print(cmd)
subprocess.run(cmd, shell=True, check=True)  # check=True会在命令执行失败时抛出异常

# 后续读取文件
with open(f"{cleaned_file_sorted_on_ts}.csv","r") as infile:
    first_line = infile.readline().strip('\n')
    print(f"First line in cleaned file = {first_line}")

如果坚持用Popen,需手动添加等待逻辑:

proc = Popen(cmd, shell=True, stdout=PIPE)
proc.wait()  # 等待shell命令执行完成后再读取文件

方法二:全程用Pandas处理(更可靠)

完全不需要依赖shell命令,Pandas本身就能完成排序并导出无表头的文件,避免跨平台问题和进程同步问题:

# 读取原文件(header=0指定原文件第一行为表头,若原文件无表头可省略该参数)
df = pd.read_csv(f"{cleaned_file}.csv", header=0, names=['r2','r5','r7','r12','r15','r70','r83'])
sorted_df = df.sort_values(by=["r2"], ascending=True)

# 导出时设置header=False,直接生成无表头的CSV
sorted_df.to_csv(f"{cleaned_file_sorted_on_ts}.csv", index=False, header=False)

# 读取验证
with open(f"{cleaned_file_sorted_on_ts}.csv","r") as infile:
    first_line = infile.readline().strip('\n')
    print(f"First line in cleaned file = {first_line}")

内容的提问来源于stack exchange,提问作者Ira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 13:05:22