开发者

How to rewrite this using 2 FOR loops?

Here is the snippet. How can I re-write this to do away with the first WHILE loop?

start = 1
end = 4
currentcount = 0
while start < end:

    file = open('C:\Users\Owner\Desktop\\test' + str(start) + '.txt')
    for line in file:    

        f = o.open('http://www.test.com/?userid=' + line.strip())
        f.close()
  开发者_运维问答      time.sleep(10)

        currentcount += 1

    start += 1


Change your while loop to this:

for i in range(start, end):

Then use i in the method body. Other points:

  • Using start as a counter is potentially confusing. If you change the value of start it is no longer the start.
  • Use a raw string for the path: r'C:\Users\Owner\Desktop\test'
  • Consider using str.format to build the string rather than string concatenation.

In Python 2.x xrange can be slightly more efficient than range, although that probably isn't a significant issue here given the size of the numbers involved.


currentcount = 0  
for i in range(1, 4):      
    file = open('C:\\Users\\Owner\\Desktop\\test' + str(i) + '.txt')      
    for line in file:               
        f = o.open('http://www.test.com/?userid=' + line.strip())          
        f.close()          
        time.sleep(10)            
        currentcount += 1

You could use some other list iteration/lambda methods, but this should be what you're looking for as it eliminates the outer while loop and is still easy to read.


currentCount = 0
for start in range(1, 4):
    file = open('C:\\Users\Owner\\Desktop\\test' + str(start) + '.txt')
    for line in file:    

        f = o.open('http://www.test.com/?userid=' + line.strip())
        f.close()
        time.sleep(10)

        currentcount += 1


A bit more complicated, but handles the most likely errors and keeps on trucking:

import time
import random

ids      = range(4)
infName  = 'c:/Users/Owner/Desktop/test{0}.txt'.format
outfAddr = 'http://www.test.com/?userid={0}'.format
delay    = lambda: time.sleep(random.randint(5,15))

filecount = 0
usercount = 0
for i in ids:
    try:
        with open(infName(i), 'r') as inf:
            filecount += 1
            for line in inf:
                try:
                    with o.open(outfAddr(line.strip())) as outf:
                        usercount += 1
                except IOError:
                    pass
                delay()
    except IOError:
        pass


My take:

start = 1
end = 4

for count in range(start,end):
    file_name=r'C:\Users\Owner\Desktop\test' + str(count) + '.txt'
    with open(file_name) as file:
        for line in file:    
            with o.open('http://www.test.com/?userid=' + line.strip()) as f:
               pass
            time.sleep(10)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜