How to import txt file contents into lists in python
I have a test.txt file and by using python I want it to be read its each line into a list and after that I want to print another text file so that list number 3 comes first. I was not able to find any good examples so therefore I come here seeking for an answer from you all. Thanks in advance for any comments.
Re: How to import txt file contents into lists in python
Here's a function that seems to do pretty-much what you want, not really very clearly written, but that's mostly cause I prefer maps and filters and such, a per-line-looping function with counters and such would, of course, work...
import string
DEFRECSEP = '================================='
DEFFIELDSEP = '\n'
DEFKEYSEP = ':'
def loadfile( filename,
recordsep = DEFRECSEP,
fieldsep= DEFFIELDSEP,
keysep=DEFKEYSEP
):
# read in whole file
tempdata = open( filename).read()
# break into records
tempdata = string.split( tempdata, recordsep )
# Get rid of extra whitespace
# and null records...
tempdata = filter( None, map( string.strip, tempdata ))
# for each record, get the field values
for i in range( len( tempdata)):
# split into the lines
fields = string.split( tempdata[i], fieldsep )
# strip trailing/leading whitespace
fields = map( string.strip, fields )
# get the key-value pairs
fields = map( string.split, fields, [ keysep ]*len(fields),
[1]*len(fields) )
# should probably do a strip here too...
tempdata[i] = fields
return tempdata
So, you get a structure that's like this
[
[
[key, value],
[key,value],
...
]
[
[key, value],
[key,value],
...
]
]
for record in dataset:
for key, value in record:
dosomething_with_key_and_value(key, value)
Incidentally, you'd probably find this kind of thing easier with a simple database module. Wouldn't be plain-text, but much easier (and faster) to use. If you really wanted convenience, you could even use shelve and just dump instances and/or data structures directly to disk so you don't need to do any parsing at all.
Re: How to import txt file contents into lists in python
You can also try importing file data into Python arrays. The array module, documented at http://python.org/doc/current/lib/module-array.html might be of interest to you anyway, as well as the numeric python extensions at http://www.pfdubois.com/numpy/ .
You will have to manipulate the lines a bit to go from strings to integers. How to do this depends on what you want. If you want a nested list like
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
something like this should work:
arr = []
inp = open ("dat.txt","r")
#read line into array
for line in inp.readlines():
# add a new sublist
arr.append([])
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the last
# element of the list
arr[-1].append(int(i))
To get a flat list like
[1, 2, 3, 4, 5, 6, 7, 8, 9]
this might do:
arr = []
inp = open ("dat.txt","r")
#read line into array
for line in inp.readlines():
# loop over the elemets, split by whitespace
for i in line.split():
# convert to integer and append to the list
arr.append(int(i))
Hope this helps.
Re: How to import txt file contents into lists in python
Depends on what you want to do. To append you can open it with "a":
Code:
with open("foo.txt", "a") as f:
f.write("new line\n")
If you want to preprend something you have to read from the file first:
Code:
with open("foo.txt", "r+") as f:
old = f.read() # read everything in the file
f.seek(0) # rewind
f.write("new line\n" + old) # write the new line before
To use the `with` statement in Python 2.5 you need to add "from __future__ import with_statement". Other than that, opening files with the `with` statement is definitely more readable and less error-prone than manual closing.