ChatGPT解决这个技术问题 Extra ChatGPT

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

如何跳过标题行并开始从 line2 读取文件?


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

如果您稍后需要标头,而不是 next(f) 使用 f.readline() 并将其存储为变量
或使用 header_line = next(f)
如果我使用 next(f) 方法,myone 会抱怨 'file' object is not an iterator。相反,f.readline() 起作用了。
@soMuchToLearnAndShare 您使用的是哪个 python 版本?最好提供重现错误的信息。
c
chriscauley
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

这将跳过 1 行。 ['a', 'b', 'c'][1:] => ['b', 'c']
@LjubisaLivac 是对的 - 这个答案适用于任何行,所以这是一个更强大的解决方案。
这很好,直到文件太大而无法读取。这对于小文件来说很好。
切片还构建内容的副本。这只是不必要的低效。
docs.python.org/3/library/itertools.html#itertools-recipes 中所述,如何使用来自 more-itertoolsconsume()?我在 stackoverflow.com/questions/11113803 上听说了这件事
s
saimadhu.polamuri

如果你想要第一行,然后你想对文件执行一些操作,这个代码会很有帮助。

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

如果不需要此行,则无需将 readline() 分配给变量。然而,我最喜欢这个解决方案。
不建议将直接读取与使用文件作为迭代器混合使用(尽管在这种特定情况下不会造成任何伤害)。
V
Vajk Hermecz

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

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

这是一个非常好的解决问题的pythonic方法,可以扩展到任意数量的标题行
这是一个非常好的执行!
奇妙的解决方案
这应该比现在得到更多的支持。
这个解决方案真的很好。这甚至适用于迭代文件对象时在内存中上传的文件。
D
Dror Hilman
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
    ...

这将一次将整个文件读入内存,因此只有在读取相当小的文件时才实用。
M
Minh Tran

为了概括读取多个标题行的任务并提高可读性,我将使用方法提取。假设您想要标记 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() 的歧义。


T
Tiago Martins Peres

如果您想从第 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's answer 的一部分)


A
Aran-Fey
# 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)