2012-05-01 30 views
5

Estoy haciendo un pequeño programa que leerá y mostrará texto de un documento. Tengo un archivo de prueba que se ve así:¿Hay alguna forma de leer un archivo .txt y almacenar cada línea en la memoria?

12,12,12 
12,31,12 
1,5,3 
... 

y así sucesivamente. Ahora me gustaría Python para leer cada línea y almacenarla en la memoria, por lo que cuando se selecciona para mostrar los datos, se mostrará entonces en el soporte como tal:

1. 12,12,12 
2. 12,31,12 
... 

y así sucesivamente. ¿Cómo puedo hacer esto?

+8

Muéstranos el código hasta el momento – Jordonias

+3

'pydoc file.readlines' – bjarneh

+1

readlines @bjarneh() no es eficiente de la memoria. –

Respuesta

13

sé que ya se contesta :) Para resumir lo anterior:

# It is a good idea to store the filename into a variable. 
# The variable can later become a function argument when the 
# code is converted to a function body. 
filename = 'data.txt' 

# Using the newer with construct to close the file automatically. 
with open(filename) as f: 
    data = f.readlines() 

# Or using the older approach and closing the filea explicitly. 
# Here the data is re-read again, do not use both ;) 
f = open(filename) 
data = f.readlines() 
f.close() 


# The data is of the list type. The Python list type is actually 
# a dynamic array. The lines contain also the \n; hence the .rstrip() 
for n, line in enumerate(data, 1): 
    print '{:2}.'.format(n), line.rstrip() 

print '-----------------' 

# You can later iterate through the list for other purpose, for 
# example to read them via the csv.reader. 
import csv 

reader = csv.reader(data) 
for row in reader: 
    print row 

imprime en mi consola:

1. 12,12,12 
2. 12,31,12 
3. 1,5,3 
----------------- 
['12', '12', '12'] 
['12', '31', '12'] 
['1', '5', '3'] 
4

Try almacenarla en una matriz

f = open("file.txt", "r") 
a = [] 
for line in f: 
    a.append(line) 
+0

forma muy simple de hacerlo. !! – Surya

+5

También conocido como 'a = open (" file.txt "). Readlines()', o más equivalente 'a = list (open (" file.txt "))'. Realmente deberías estar usando una declaración 'with' para cerrar el archivo; esto depende de la semántica de recuento de ref de CPython para hacerlo y no funcionará como se espera en virtud de, p. PyPy. – Dougal

+0

¿no tiene problemas si el texto es muy grande con más líneas en el archivo? – Surya

1

Usted también puede estar interesado en el módulo csv. Le permite analizar sintácticamente, leer y escribir en archivos en los valores separados por comas (CSV) ..., que tu ejemplo parece estar en

Ejemplo:.

import csv 
reader = csv.reader(open('file.txt', 'rb'), delimiter=',') 
#Iterate over each row 
for idx,row in enumerate(reader): 
    print "%s: %s"%(idx+1,row) 
0
with open('test.txt') as o: 
    for i,t in enumerate(o.readlines(), 1): 
     print ("%s. %s"% (i, t)) 
0
#!/usr/local/bin/python 

t=1 

with open('sample.txt') as inf: 
    for line in inf: 
     num = line.strip() # contains current line 
     if num: 
      fn = '%d.txt' %t # gives the name to files t= 1.txt,2.txt,3.txt ..... 
      print('%d.txt Files splitted' %t) 
      #fn = '%s.txt' %num 
      with open(fn, 'w') as outf: 
       outf.write('%s\n' %num) # writes current line in opened fn file 
       t=t+1 
1

Gracias por @PePr excelente solución. Además, puede intentar imprimir el archivo .txt con el método integrado String.join(data). Por ejemplo:

with open(filename) as f: 
    data = f.readlines() 
print(''.join(data)) 
Cuestiones relacionadas