从第 2 行读取文件或跳过标题行

2025-02-25 09:07:00
admin
原创
25
摘要:问题描述:我怎样才能跳过标题行并从第二行开始读取文件?解决方案 1:with open(fname) as f: next(f) for line in f: #do something 解决方案 2:f = open(fname,'r') lines = f.readline...

问题描述:

我怎样才能跳过标题行并从第二行开始读取文件?


解决方案 1:

with open(fname) as f:
    next(f)
    for line in f:
        #do something

解决方案 2:

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

解决方案 3:

如果您想要第一行,然后想要对文件执行某些操作,那么此代码将会有所帮助。

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

解决方案 4:

如果切片可以在迭代器上起作用......

from itertools import islice
with open(fname) as f:
    for line in islice(f, 1, None):
        pass

解决方案 5:

f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...

解决方案 6:

如果你想从第 2 行开始读取多个 CSV 文件,这个方法很管用

for files in csv_file_list:
        with open(files, 'r') as r: 
            next(r)                  #skip headers             
            rr = csv.reader(r)
            for row in rr:
                #do something

(这是Parfait对另一个问题的回答的一部分)

解决方案 7:

为了概括读取多个标题行的任务并提高可读性,我将使用方法提取。假设您想要标记前三行coordinates.txt以用作标题信息。

例子

coordinates.txt
---------------
Name,Longitude,Latitude,Elevation, Comments
String, Decimal Deg., Decimal Deg., Meters, String
Euler's Town,7.58857,47.559537,0, "Blah"
Faneuil Hall,-71.054773,42.360217,0
Yellowstone National Park,-110.588455,44.427963,0

然后方法提取允许您指定要对标题信息执行的操作(在此示例中,我们只是根据逗号对标题行进行标记并将其作为列表返回,但还有更多操作可以做)。

def __readheader(filehandle, numberheaderlines=1):
    """Reads the specified number of lines and returns the comma-delimited 
    strings on each line as a list"""
    for _ in range(numberheaderlines):
        yield map(str.strip, filehandle.readline().strip().split(','))

with open('coordinates.txt', 'r') as rh:
    # Single header line
    #print next(__readheader(rh))

    # Multiple header lines
    for headerline in __readheader(rh, numberheaderlines=2):
        print headerline  # Or do other stuff with headerline tokens

输出

['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']

如果coordinates.txt包含另一个标题行,只需更改numberheaderlines。最重要的是,它清楚地表明了__readheader(rh, numberheaderlines=2)正在做什么,并且我们避免了必须弄清楚或评论为什么接受答案的作者next()在他的代码中使用了的歧义。

解决方案 8:

# Open a connection to the file
with open('world_dev_ind.csv') as file:

    # Skip the column names
    file.readline()

    # Initialize an empty dictionary: counts_dict
    counts_dict = {}

    # Process only the first 1000 rows
    for j in range(0, 1000):

        # Split the current line into a list: line
        line = file.readline().split(',')

        # Get the value for the first column: first_col
        first_col = line[0]

        # If the column value is in the dict, increment its value
        if first_col in counts_dict.keys():
            counts_dict[first_col] += 1

        # Else, add to the dict and set value to 1
        else:
            counts_dict[first_col] = 1

# Print the resulting dictionary
print(counts_dict)
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1492  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1344  
  IPD(Integrated Product Development)流程是一套先进的产品开发管理体系,旨在通过整合跨部门资源,实现产品的高效开发与交付。在IPD流程中,确保项目按时交付是至关重要的,它直接关系到企业的市场竞争力和客户满意度。以下将从多个关键方面探讨如何在IPD流程阶段确保项目按时交付。精准的项目规划项...
IPD流程分为几个阶段   2  
  IPD(Integrated Product Development)流程是一套先进的产品开发管理体系,旨在缩短产品上市时间、提高产品质量、降低成本并增强企业的市场竞争力。深入理解IPD流程阶段的关键要素,对于企业成功实施IPD,实现产品开发的高效运作至关重要。IPD流程的概念与重要性IPD流程强调将产品开发视为一个整...
IPD测试流程   3  
  IPD(Integrated Product Development)产品开发流程是一套先进的、旨在提高产品开发效率与质量的管理体系。在这个体系中,评审环节起着至关重要的作用,它们如同关卡,确保产品在各个阶段都朝着正确的方向前进,符合市场需求和企业战略。其中有四个评审环节尤为关键,它们分别在不同阶段对产品进行全面审视,...
研发IPD流程   5  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

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

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

内置subversion和git源码管理

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

免费试用