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

2025-01-09 08:47:00
admin
原创
107
摘要:问题描述:我正在使用下面提到的代码通过 Python 编辑 csv。代码中调用的函数构成了代码的上半部分。问题:我希望下面引用的代码从第二行开始编辑 csv,我希望它排除包含标题的第一行。现在它只在第一行应用函数,而我的标题行正在发生变化。in_file = open("tmob_notcleane...

问题描述:

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

请帮我解决这个问题。


解决方案 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)

解决方案 2:

解决这个问题的另一种方法是使用 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'])

解决方案 3:

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

您想要next(reader)跳过一行。

解决方案 4:

只需使用 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  

解决方案 5:

受到 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())

解决方案 6:

with open(filename, 'r') as file:
    reader = csv.DictReader(file, fieldnames=None)
    # for some reason fieldnames=None causes first row to be skipped
    for row in reader: 
        print(row) # so the the first row printed is second row in file
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2525  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1542  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Filestage、Xebrio、Kintone、Monday、Celoxis、Backlog、BubblePPM、Plutio、Scoro。在当今快速变化的商业环境中,项目管理系统的选择成为企业成功的关键因素之一。许多企业在选购项目管理系统时,常常面临功能复杂、...
项目管理系统   0  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Plutio、Kantata、Kintone、LiquidPlanner、Motion、Smartsheet、Targa、QuickBase、Hive。在当今快节奏的商业环境中,项目管理软件已成为企业提升效率、优化资源分配和确保项目按时交付的关键工具。然而,面对市...
开源项目管理软件   15  
  本文介绍了以下10款项目管理软件工具:禅道项目管理软件、Scoro、Wekan、Hubstaff、Kintone、Wrike、Filestage、Trello、Airtable、Paymo。在当今快节奏的商业环境中,项目管理已成为企业成功的关键因素之一。然而,许多项目经理和团队在管理复杂项目时常常面临诸多挑战,如任务分...
项目管理系统   7  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用