Search code examples
python-3.xrandomreadlines

How to select random line in file using readlines() with a previously random generated integer?


I've got some code for a specific goal, to load a page with a proxy, chosen from a list via random number. Every time I run it, the same proxy is selected from the list, even though it's a different random integer every time.

I've got the code working to an extent, the random number generation works, when debugging it will be a different random number each time. I've checked multiple times, and the proxServRaw variable is always the same IP, no matter how many times it's been run. Same with the port selection.

As far as I know from various tutorials and the documentation, this is the correct syntax for what I need, but maybe I'm wrong. I'm still fairly new at this, this is really my first project. Here's the block that's giving me trouble.

def adProxy():
random.seed()
randProx = random.randint(1,156) #this part works, different number every time
proxList = open('/home/ivan/Documents/programs/adHack/proxyIP.txt', 'r')
proxServRaw = proxList.readline(randProx)
proxServIP = proxServRaw.rstrip('\n') #this variable does not change ever
proxPortList = open('/home/ivan/Documents/programs/adHack/proxyport.txt', 'r')
proxServPortRaw = proxPortList.readline(randProx)
proxServPort = proxServPortRaw.rstrip('\n')
proxList.close()
proxPortList.close()
global proxServComp #should make global for other functions
proxServComp = f'--proxy-server=socks://{proxServIP}:{proxServPort}'
import pdb; pdb.set_trace()

An example of the debug:

   (Pdb) p randProx
     52
   (Pdb) p proxServIP
     '115.79.63.188'

and a second time after exiting and reloading:

(Pdb) p randProx
136
(Pdb) p proxServIP
'115.79.63.188'
(Pdb)

Supposedly since I've got a different number it should choose a different server from the list, which is about 150 in total, all different, after I culled it manually to be safe.

So yeah any help would be appreciated.


Solution

  • You should use linecache to read specific line from a file instead of readline. Examples is:

    import linecache
    
    data = linecache.getline('test.txt', 3)