回答:
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
['a', 'b', 'c'][1:]
=>['b', 'c']
consume()
れmore-itertools
ているようにfromを使用するのはどうですか?これについては、stackoverflow.com
複数のヘッダー行を読み取るタスクを一般化して読みやすくするために、メソッド抽出を使用します。の最初の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()
が自分のコードで使用する理由を理解またはコメントする必要があるというあいまいさを回避します。
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
(これは別の質問に対するパフェの回答の一部です)
# 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)
next(f)
使用f.readline()
し、変数として保存