Answers:
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
['a', 'b', 'c'][1:]
=>['b', 'c']
consume()
from ?我在stackoverflow.com/questions/11113803上听说过more-itertools
为了概括读取多个标题行的任务并提高可读性,我将使用方法提取。假设您想标记化前三行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()
它并将其存储为变量