我正在使用下面引用的代码来使用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.

如果您想将头文件写入未经处理的输出文件,这也很简单,将输出next()传递到writer.writerow():

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

Python相关问答推荐

错误:找不到TensorFlow / Cygwin的匹配分布

Ibis中是否有一个ANY或ANY_UTE表达,可以让我比较子查询返回的一组值中的值?

Polars Select 多个元素产品

了解shuffle在NP.random.Generator.choice()中的作用

绘制系列时如何反转轴?

Python panda拆分列保持连续多行

DuckDB将蜂巢分区插入拼花文件

有什么方法可以避免使用许多if陈述

Pandas 第二小值有条件

使用新的类型语法正确注释ParamSecdecorator (3.12)

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

时间序列分解

将输入管道传输到正在运行的Python脚本中

在Wayland上使用setCellWidget时,try 编辑QTable Widget中的单元格时,PyQt 6崩溃

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

实现神经网络代码时的TypeError

计算天数

为什么np. exp(1000)给出溢出警告,而np. exp(—100000)没有给出下溢警告?

为什么\b在这个正则表达式中不解释为反斜杠

为什么'if x is None:pass'比'x is None'单独使用更快?