Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to read a .txt file and store each line to memory?

Tags:

python

file

I am making a little program that will read and display text from a document. I have got a test file which looks like this:

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

and so on. Now I would like Python to read each line and store it to memory, so when you select to display the data, it will display it in the shell as such:

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

and so on. How can I do this?

like image 917
EatMyApples Avatar asked May 01 '12 03:05

EatMyApples


People also ask

How do I read a text file line?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you read a file in Python and store it in a list?

You can read a text file using the open() and readlines() methods. To read a text file into a list, use the split() method. This method splits strings into a list at a certain character.

How do I get data from a text file?

You can import data from a text file into an existing worksheet. Click the cell where you want to put the data from the text file. On the Data tab, in the Get External Data group, click From Text. In the Import Data dialog box, locate and double-click the text file that you want to import, and click Import.


1 Answers

I know it is already answered :) To summarize the above:

# 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

It prints on my console:

 1. 12,12,12
 2. 12,31,12
 3. 1,5,3
-----------------
['12', '12', '12']
['12', '31', '12']
['1', '5', '3']
like image 89
pepr Avatar answered Oct 28 '22 01:10

pepr