Odpowiedzi:
with open(fname) as f:
next(f)
for line in f:
#do something
header_line = next(f).
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
['a', 'b', 'c'][1:]=>['b', 'c']
consume()z używaniem z, more-itertoolsjak stwierdzono w docs.python.org/3/library/itertools.html#itertools-recipes ? Słyszałem o tym na stackoverflow.com/questions/11113803
Jeśli potrzebujesz pierwszej linii, a następnie chcesz wykonać operację na pliku, ten kod będzie pomocny.
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
Jeśli krojenie może działać na iteratorach ...
from itertools import islice
with open(fname) as f:
for line in islice(f, 1, None):
pass
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
...
Aby uogólnić zadanie odczytu wielu linii nagłówka i poprawić czytelność, użyłbym metody ekstrakcji. Załóżmy, że chcesz tokenizować trzy pierwsze wiersze w coordinates.txtcelu użycia jako informacji nagłówka.
Przykład
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
Następnie wyodrębnianie metody pozwala określić, co chcesz zrobić z informacjami nagłówka (w tym przykładzie po prostu tokenizujemy linie nagłówka na podstawie przecinka i zwracamy go jako listę, ale jest miejsce na wiele więcej).
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
Wynik
['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']
Jeśli coordinates.txtzawiera inny nagłówek, po prostu zmień numberheaderlines. Co najlepsze, jasne __readheader(rh, numberheaderlines=2)jest, co się dzieje, i unikamy dwuznaczności, że musimy wymyślić lub skomentować, dlaczego autor akceptowanej odpowiedzi używa next()w swoim kodzie.
Jeśli chcesz odczytać wiele plików CSV, zaczynając od linii 2, działa to jak urok
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
(jest to część odpowiedzi Parfait na inne pytanie)
# 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)używaćf.readline()i przechowywać jako zmienną