Skip to content Skip to sidebar Skip to footer

If I Get A Random Line Is It Possible To Get The Line 2 Below It?

If i get a random line through this code: import random import time with open('Songs.txt','r') as f: for i in range(random.randint(1,8)): line = f.readline() print('T

Solution 1:

In your specific code, you can get the line two below the selected line like this:

import random

withopen("Songs.txt","r") as f:
    for i inrange(random.randint(1,8)):
        line = f.readline()
    next(f, None)
    two_below = next(f, None)

print(line, end='')
print(two_below, end='')

Example output:

C
E

More generally, you can consider using the linecache module for random access to text lines.

Demo:

>>>import linecache>>>import random>>>>>>rand_line = random.randint(1, 8)>>>rand_line
3
>>>linecache.getline('Songs.txt', rand_line)
'C\n'
>>>linecache.getline('Songs.txt', rand_line + 2)
'E\n'
>>>linecache.getline('Songs.txt', 1000)
''

Solution 2:

One solution would be to store all lines in memory with lines = list(f) and then if your random number is i getting the line you want would be simply lines[i+2]. Something like this:

import random

with open("Songs.txt","r") as f:
    lines = list(f)

i = random.randint(1, 8)
print("The First Letter Is:",lines[i][0])
print("Other letter is:", lines[i+2])

Post a Comment for "If I Get A Random Line Is It Possible To Get The Line 2 Below It?"