[Tutor] Grabbing Info from Text files?

Christian Witts cwitts at compuscan.co.za
Fri Nov 12 10:50:41 CET 2010

On 12/11/2010 08:28, Michael Stover wrote:
> Hello,
> I have been getting lost when trying to find the needed information on 
> how to grab information from text files to be used in a python script 
> I am working on. Essentially the script is calling upon other programs 
> to grab specific information about files and putting that information 
> into basic text files. When I say basic I mean basic, each piece of 
> information has its own line such as:
> InfoOne=?
> InfoTwo=?
> Where the ? is a value ranging from 1 character up to 5 (usually 
> numbers), and it is the value I represented with ? that I need to 
> grab. I am hoping it is possible to grab 1 line at a time so variables 
> can be set for use later in my script.
> I have tried to "decipher" the python documents on this, but honestly, 
> being a dabbler in python I am getting "lost, dazed and confused" as 
> friends would put it.
> Thankfully this is not for any homework assignments, it is merely a 
> script I am working on for making some repetitive tasks more 
> automated, such as grabbing information about video files, and if 
> needed convert them. I have yet to find a program that does what I am 
> aiming for so I started creating a python script (as python is already 
> installed on my Linux distro). It just seems to have become more 
> complicated that I had hoped, but I am at a point now were I do not 
> want to leave it unfinished. If an example of my script is needed I am 
> more than willing to provide it for clarification of what I am trying 
> to do.
> Thanks,
> Mike
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

If you can ensure that a header is written to those text files so 
they're in format such as

then you can take a look at the ConfigParser module where you would 
simply read the file and all your values would be read in in neat pairs.

$ cat test.conf

$ python
Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> from ConfigParser import ConfigParser
 >>> cfg = ConfigParser()
 >>> cfg.read('test.conf')
 >>> cfg.items('Blah')
[('optone', '1'), ('optthree', '3'), ('opttwo', '2')]

The other way to do it yourself is to iterate over the lines in the 
file, split the key and value and store it in a dictionary for later use.

Kind Regards,
Christian Witts

More information about the Tutor mailing list