265

我正在使用下面提到的代码来使用 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但它没有用。

请帮我解决这个问题。

4

5 回答 5

452

您的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)
于 2013-01-10T12:07:53.553 回答
146

解决这个问题的另一种方法是使用 DictReader 类,它“跳过”标题行并使用它来允许命名索引。

给定“foo.csv”如下:

FirstColumn,SecondColumn
asdf,1234
qwer,5678

像这样使用 DictReader:

import csv
with open('foo.csv') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        print(row['FirstColumn'])  # Access by column header instead of column number
        print(row['SecondColumn'])
于 2015-03-19T23:37:41.427 回答
10

这样做row=1不会改变任何事情,因为您只会用循环的结果覆盖它。

你想next(reader)跳过一行。

于 2013-01-10T12:06:24.597 回答
2

只需使用 next() 迭代一次

with open(filename) as file:

    csvreaded = csv.reader(file)
    header = next(csvreaded)

    for row in csvreaded:
        empty_list.append(row) #your csv list without header  

或在阅读器对象的末尾使用 [1:]

with open(filename) as file:

    csvreaded = csv.reader(file)
    header = next(csvreaded)

    for row in csvreaded[1:]:
        empty_list.append(row) #your csv list without header  
于 2021-08-26T16:00:13.197 回答
0

灵感来自 Martijn Pieters 的回应。

如果您只需要从csv文件中删除标题,则使用标准 Python 文件 I/O 库编写可以更有效地工作,避免使用 CSV Python 库编写:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   next(infile)  # skip the headers
   outfile.write(infile.read())
于 2020-10-30T18:18:43.683 回答