How to read random line from txt file without writing lines of the file to the list?

I have a text file that contains 33723 line. Write all these strings in the list will be expensive, so you need to read a random row from this txt file, not writing all the rows in the list.

How to implement it?
March 25th 20 at 12:40
4 answers
March 25th 20 at 12:42
Solution
The problem is that when opening the file, we get the io stream.TextIOBase with the cursor at the beginning. The newline is an ordinary character (or characters), and even knowing the line number that we are interested in, you need to read the file to understand where end of one line and starts another. At io.TextIOBase has the readline method, you can use them in a loop in order to skip the extra lines in the memory this will be only the current line. If we knew the character position where the search string starts, it would be possible to use the seek method.
Let's say we need a line 100 will get something like:
f = open('file.txt')
for i in range(100):
 line = f.readline()
print(line)
- Noemie.Monahan commented on March 25th 20 at 12:45
@Noemie.Monahan, ie I need to generirovanie a random number from 1 to 33723 and start the cycle up to this number? - Samir.Kautzer commented on March 25th 20 at 12:48
@Samir.Kautzer, Yes, just in the last passage in line is the search string. - Noemie.Monahan commented on March 25th 20 at 12:51
March 25th 20 at 12:44
Solution
StackOverflow

import random
print(random.choice(list(open('file.txt'))))
Write all these strings in the list will be expensive
- verdie_Oberbrunner55 commented on March 25th 20 at 12:47
@verdie_Oberbrunner55,

The same page on the stack:

Without loading the file into RAM - reese85 commented on March 25th 20 at 12:50
March 25th 20 at 12:46
Solution
linecache — Random access to text lines
linecache.getline('textfile.txt', random.randint(0, 33723))
March 25th 20 at 12:48
Why to drive the row in the database and to read the line on the aydishnik not want?
It was not possible to use a database with python - Samir.Kautzer commented on March 25th 20 at 12:51

Find more questions by tags Python