[Tutor] newbie: Reading text file

ALAN GAULD alan.gauld at btinternet.com
Fri Jun 1 10:42:18 CEST 2007

Hi Grant,

> I'm a newbie and this is my first script submission to this email list.
> I was able to parse out the jobs list into a string: "jobs = [ . . ."
> However, I can't make python interpret that string as the command "jobs = [ some list]"

There are ways of doing that but unless you are specifically doing that 
as a challenge it is much easier just to import your py file. When you 
import a module Python will evaluate the contents as Python code 
and the variables in the module become available to you. That way 
you don't need to read the file manually.

The only caveat with the import method is that Python needs to find 
our module so it must either be in the same folder as your python 
script or the folder must be in the sys.path variable. Thus for a general solution:

import sys
import myfile    # no .py
jobs = myfile.jobs

And that should be it. jobs should now contain the same list that 
was in your myfile.py

However if you do want todo it the hard way:

> # open the file and assign it to the variable "thefile"
> thefile = open("/home/banter/Desktop/mylist.py") 

OK To here but....

> # read the file and assign it to the variable "read_thefile"

> read_thefile = file.read(thefile)
> # make the file's contents into a string
> string_thefile = str(read_thefile)

this should simply be

data = thefile.read()

# split that string up into a list
splitlist = data.split()

# index the list to find the placement of the word 'jobs'
it_starts = splitlist.index('jobs')

# index the list to find the placement of the ']'

OK Now its getting rather messy. Its probably easier to take a 
completely different approach, something like(untested code!):

started = False
for line in file(myfile.py'):
     if 'jobs' in line and not started:
        jobs = []
        started = True
    if ']' not in line and started:
    else: break

> are you getting a duplicate copy of this email? 
> I am CCing 
tutor at python and TOing you . . .

Yes that's the correct procedure. Use ReplyAll in your mail tool 
and all should be well. (although some folks would prefer if you 
just reply to the list, it's a bit of a hot topic! :-)


Alan G.

Which email service gives you unlimited storage?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070601/f63e182c/attachment.htm 

More information about the Tutor mailing list