[Tutor] Two questions
Andrei Kulakov
ak@silmarill.org
Sat, 13 Apr 2002 10:11:32 -0400
On Sat, Apr 13, 2002 at 08:23:31AM -0500, Henry Steigerwaldt wrote:
> To Whom It May Concern:
>
> The program I am about to describe is opened in Idle, and then run in
> Idle. The code pieces below are all located in a function called Main().
>
> The following piece of code works just fine:
>
> # read first line in a file to get URL
> site_url = fileobject.readline()
> print "site_url = ", url
>
> In the above code, the URL read in first line of a file stores just fine
> into variable "site_url." However, when I try to store the URL into a
> list or tuple, I get an error.
>
> Below is the piece of code to store URL into a list:
>
> i = 0
> site_url[i] = fileobject.readline()
> print "site_url = ", site_url[i]
>
Here's how it's done:
site_url = [fileobject.readline()]
OR
line = fileobject.readline()
site_url = [line]
OR
site_url = []
site_url.append(fileobject.readline())
>
> Here is the error that is output in Idle:
>
> Main()
> File "C:\python_pgms\misc_obs_pgm.py", line 37, in Main
> site_url[i] = fileobject.readline()
> NameError: global name 'site_url' is not defined
> _________________________________
> Below is the piece of code to store URL into a tuple:
>
> i = 0
> site_url(i) = fileobject.readline()
> print "site_url = ", site_url(i)
>
Although you probably don't want to do this at all:
site_url = (fileobject.readline(),)
>
> Here is the error that is output in Idle:
>
> File "C:\python_pgms\misc_obs_pgm.py", line 37
> site_url(i) = fileobject.readline()
> SyntaxError: can't assign to function call
> ______________________________________________
>
> I do not understand why I am getting these errors.
>
> Actually what I want to do in this program is read the first
> line of a file, which contains a number, say 4. The number tells
> the program how many URLs will follow (one per line) in the file.
> So after the first line of the file is read, the program then is
> supposed to read and then store the URLs in either a list or
> a tuple. After that, I want to go to each site (URL) and grab
> some information.
>
You probably don't need the number, just read in the lines and if they
start with http or www, add them to URL list:
site_url = []
while 1:
l = fileobject.readline()
if l.startswith("http") or l.startswith("www"):
site_url.append(l.strip()) # strip because I think it will
# have \n at the end otherwise.
If you really need the number:
n = fileobject.readline()
num = int(n.strip())
>
> Please be as least cryptic as possible in any response. I have
> written some small programs in Tcl/Tk (and a couple of other
> languages in the past), but my programming experience is very
> limited.
>
> Thanks for any help provided !
>
> Henry Steigerwaldt
> Hermitage, TN
>
--
Cymbaline: intelligent learning mp3 player - python, linux, console.
get it at: cy.silmarill.org