2行目からファイルを読み取るか、ヘッダー行をスキップします


242

ヘッダー行をスキップして、line2からファイルの読み取りを開始するにはどうすればよいですか?

回答:


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

51
後でヘッダが必要な場合は、代わりにnext(f)使用f.readline()し、変数として保存
のろわ

36
またはを使用しますheader_line = next(f)
Samuel

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

これは1行スキップします。['a', 'b', 'c'][1:]=>['b', 'c']
Eric Duminil 2017年

3
@LjubisaLivacは正解です-この答えは一般的なものなので、これははるかに強力なソリューションです。
Daniel Soutar

17
これは、ファイルが大きすぎて読み取れないまでは問題ありません。これは小さなファイルには問題ありません。
CppLearner 2018

1
スライスはコンテンツのコピーも作成します。これは単に不必要に非効率的です。
chepner

docs.python.org/3/library/itertools.html#itertools-recipesに記述さconsume()more-itertoolsているようにfromを使用するのはどうですか?これについては、stackoverflow.com
questions / 11113803で

24

最初の行が必要で、ファイルに対して何らかの操作を実行したい場合は、このコードが役立ちます。

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

この行が不要な場合は、変数にreadline()を割り当てる必要はありません。ただし、このソリューションが一番好きです。
アンナ

直接読み取りとイテレーターとしてのファイルの使用を混在させることはお勧めしません(ただし、この特定のケースでは害はありません)。
chepner

9

イテレータでスライスが機能する場合...

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

1
これは問題を解決する非常に優れたpythonicの方法であり、任意の数のヘッダー行に拡張できます
Dai

これは本当に素晴らしい実行です!
ディーゼル

マーベラスソリューション
ラス・ハイド

これは、現在よりもはるかに賛成されるべきです。
chepner

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

2
これはファイル全体を一度にメモリに読み込むため、かなり小さなファイルを読み込む場合にのみ実用的です。
ヘイデンシッフ

1

複数のヘッダー行を読み取るタスクを一般化して読みやすくするために、メソッド抽出を使用します。の最初の3行をトークン化して、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()が自分のコードで使用する理由を理解またはコメントする必要があるというあいまいさを回避します。



0
# 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)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.