kimpster kimpster - 22 days ago 6
Python Question

Python variable/count not increasing

My code attempts to create a folder which then downloads a pdf to the corresponding folder. In my current code the variable and counter "i" keeps track of which folder to download to but it seems to not be updating for some reason. At the end of the else if statement I want the variable i to increase by 1. Not understanding what the issue is here, I'm fairly new to python and if a similar situation was coded in java I know this would work just file but not sure why it's not working in python.

import re
import os
import urllib
f = open("newfile.txt")
suffix = '.pdf'
for line in f:
i = 0
folderopt = str(i)


if suffix in line:
print('download')
url = line.rstrip('\n')
pdfname = url.split('LTN',1)[1]
print ('download to:'+'/Users/user/Desktop/PDF/'+folderopt+'/'+pdfname)
urllib.urlretrieve(url,'/Users/user/Desktop/PDF/'+folderopt+'/'+pdfname)
elif line>i:

filename = line.rstrip('\n')
print ('code:'+filename)
os.mkdir('/Users/user/Desktop/PDF/'+filename)
global i
i = i+1
f.close


EDIT: I put the variable outside of the for loop still getting this

IOError: [Errno 2] No such file or directory: '/Users/user/Desktop/PDF/0/20160412398.pdf'


the i count has not increased even though the folder /Users/user/Desktop/PDF/1 was created.

changed elif statement to

elif int(line.rstrip('\n'))>i


still not working

Answer

You set i to 0 in the loop,try this:

import re
import os
import urllib
f = open("newfile.txt")
suffix = '.pdf'
i = 0
for line in f:
    folderopt = str(i)

    if suffix in line:
        print('download')
        url = line.rstrip('\n')
        pdfname = url.split('LTN',1)[1]
        print ('download to:'+'/Users/user/Desktop/PDF/'+folderopt+'/'+pdfname)
        urllib.urlretrieve(url,'/Users/user/Desktop/PDF/'+folderopt+'/'+pdfname)
    elif line>i:

        filename = line.rstrip('\n')
        print ('code:'+filename)
        os.mkdir('/Users/user/Desktop/PDF/'+filename)
        global i
        i+= 1
f.close