Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 16-05-2009
Member
 
Join Date: Sep 2005
Posts: 229
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.
Reply With Quote
  #2  
Old 16-05-2009
Member
 
Join Date: Jun 2006
Posts: 620
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.
Reply With Quote
  #3  
Old 16-05-2009
Member
 
Join Date: Dec 2007
Posts: 1,592
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.
Reply With Quote
  #4  
Old 16-05-2009
Member
 
Join Date: Oct 2005
Posts: 2,357
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.
__________________
I'm the Proud Owner of the most dangerous weapon
known to man kind: Human Brain
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "How to import txt file contents into lists in python"
Thread Thread Starter Forum Replies Last Post
How to save file and run file using python Statuser Software Development 3 21-07-2011 08:02 AM
How to read a file in reverse order in python? MKAIF Software Development 5 20-02-2010 06:56 PM
Regular Expressions on the Contents of a File samualres Software Development 4 19-02-2010 10:30 PM
Windows 7 search does not return file contents Benedict Operating Systems 3 05-12-2009 10:38 AM
Display Contents of XML File fastrod Software Development 3 14-03-2009 12:52 PM


All times are GMT +5.5. The time now is 05:47 AM.