Lea el archivo desde la línea 2 u omita la fila del encabezado
¿Cómo puedo saltarme la fila del encabezado y empezar a leer un archivo desde line2?
8 answers
with open(fname) as f:
next(f)
for line in f:
#do something
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-25 17:26:45
f = open(fname,'r')
lines = f.readlines()[1:]
f.close()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-25 17:29:40
Si desea la primera línea y luego desea realizar alguna operación en el archivo, este código será útil.
with open(filename , 'r') as f:
first_line = f.readline()
for line in f:
# Perform some operations
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-07 16:18:03
f = open(fname).readlines()
firstLine = f.pop(0) #removes the first line
for line in f:
...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-25 17:36:27
Si el corte podría funcionar en iteradores...
from itertools import islice
with open(fname) as f:
for line in islice(f, 1, None):
pass
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-15 13:06:44
with open('old.csv', 'r') as f, open('new.csv', 'w') as ff:
first_line = f.readline()
for line in f:
line = line.translate({ord(i):None for i in 'abcd'})
ff.write(line)
ff.seek(0)
ff.write(first_line)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-17 14:40:31
# 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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-15 06:09:26
Para generalizar la tarea de leer varias líneas de encabezado y mejorar la legibilidad, usaría extracción de métodos. Supongamos que desea tokenizar las tres primeras líneas de coordinates.txt
para usar como información de encabezado.
Ejemplo
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
Entonces la extracción del método le permite especificar lo que desea hacer con la información del encabezado (en este ejemplo, simplemente tokenizamos las líneas del encabezado en función de la coma y las devolvemos como una lista, pero hay espacio para hacer mucho más).
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
Salida
['Name', 'Longitude', 'Latitude', 'Elevation', 'Comments']
['String', 'Decimal Deg.', 'Decimal Deg.', 'Meters', 'String']
Si coordinates.txt
contiene otra línea de encabezado, simplemente cambie numberheaderlines
. Lo mejor de todo es que está claro lo que __readheader(rh, numberheaderlines=2)
está haciendo y evitamos la ambigüedad de tener que averiguar o comentar por qué el autor de la respuesta aceptada usa next()
en su código.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-26 16:11:12