python - 使用 Python 处理 csv 文件时如何跳过标题?

我正在使用下面提到的代码来使用 Python 编辑 csv。代码中调用的函数构成了代码的上半部分。

问题:我希望下面提到的代码从第二行开始编辑 csv,我希望它排除包含标题的第一行。现在它只在第一行应用函数,我的标题行正在改变。

in_file = open("tmob_notcleaned.csv", "rb")
reader = csv.reader(in_file)
out_file = open("tmob_cleaned.csv", "wb")
writer = csv.writer(out_file)
row = 1
for row in reader:
    row[13] = handle_color(row[10])[1].replace(" - ","").strip()
    row[10] = handle_color(row[10])[0].replace("-","").replace("(","").replace(")","").strip()
    row[14] = handle_gb(row[10])[1].replace("-","").replace(" ","").replace("GB","").strip()
    row[10] = handle_gb(row[10])[0].strip()
    row[9] = handle_oem(row[10])[1].replace("Blackberry","RIM").replace("TMobile","T-Mobile").strip()
    row[15] = handle_addon(row[10])[1].strip()
    row[10] = handle_addon(row[10])[0].replace(" by","").replace("FREE","").strip()
    writer.writerow(row)
in_file.close()    
out_file.close()

我试图通过将 row 变量初始化为 1 来解决这个问题,但没有成功。

请帮我解决这个问题。

最佳答案

您的reader变量是一个可迭代的,通过循环它可以检索行。

要让它在循环前跳过一项,只需调用 next(reader, None) 并忽略返回值。

您还可以稍微简化代码;使用打开的文件作为上下文管理器来自动关闭它们:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

如果您想将 header 写入未处理的输出文件,这也很容易,传递 next() 的输出至writer.writerow() :

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

https://stackoverflow.com/questions/14257373/

相关文章:

python - 如何为类对象创建自定义字符串表示?

python - Python中的退出代码

linux - 在 linux 中显示磁盘事件的类似 htop 的工具

linux - 如何阅读 shell 命令的源代码?

linux - 在一行中从 linux 终端发送邮件

linux - 什么是不间断进程?

python - 遍历列表中的每两个元素

mysql - 无法连接到 MySQL 服务器错误 111

Python 函数属性 - 使用和滥用

python - 在 Python 中创建具有初始容量的列表