Max00355
Max00355

Reputation: 867

Why does my code keep stopping?

I made a Python script, that reads a text file then goes to a url, and adds the extension in the text file to the url. The problem is the script keeps stopping before it is done reading the file. I cant figure out why.

import urllib
f = open("extension/1.txt", 'r')

for x in f.readline():    
    a = f.readline()
    url = "http://www.link.com/whatever/%s" % a
    print url
    urllib.urlretrieve(url, a) 

Upvotes: 1

Views: 196

Answers (3)

kindall
kindall

Reputation: 184211

Your code does the following:

  1. Reads one line from the file (f.readline()).
  2. For each character in that line (for x in f.readline()), read an additional line (a = f.readline()) and process it.

Thus, it will only process as many lines as there are characters in the first line of the file, and the first line will never be processed.

You probably want to write that loop as:

with open("extension/1.txt") as f:
    for a in f:
        a = a.strip()
        url = "http://www.link.com/whatever/%s" % a
        print url
        urllib.urlretrieve(url, a) 

Upvotes: 2

bossylobster
bossylobster

Reputation: 10163

By calling for x in f.readline():, you'll be going through the string that is the first line of the file as an iterable and then grabbing a new line for each character in the first line via a = f.readline(). I don't think this is your intent.

The file object f is iterable itself, so you can simply do the following:

for line in f:
    value = line.rstrip('\n')
    url = "http://www.link.com/whatever/%s" % value
    print url
    urllib.urlretrieve(url, value)  # Not sure why you want to send value (your a) here

Upvotes: 6

user1356386
user1356386

Reputation:

Perhaps reading all the lines at first like so:

fp = open(the_file)
lines = fp.readlines()
fp.close()

for line in lines:
    do something

Upvotes: 0

Related Questions