1

I am working on a word guessing game and I have created a text file with each line being a word (it's 1000 lines).

I don't want to get the whole text file into memory. I just want to read a random line of the text file and put it into a string.

I did a quick search and everybody was reading the whole file into memory and getting a random line from there but I want to read a random line in form of a string.

pjs
  • 18,696
  • 4
  • 27
  • 56
Emad
  • 13
  • 3
  • 2
    Possible duplicate of [How do i make python choose randomly one line after the first line of a file?](https://stackoverflow.com/questions/57295310/how-do-i-make-python-choose-randomly-one-line-after-the-first-line-of-a-file) – tim Aug 31 '19 at 13:03
  • 1
    I do NOT think this is a duplicate of the linked question, because this questions asks about not reading the whole file into memory and the linked answers all read the whole file. – Ralf Aug 31 '19 at 14:57
  • 1
    @Ralf if reading the entire file is both the simplest and most performant way to get the answer, why wouldn't it suffice? "I don't want to read the whole text file" isn't a good reason to dismiss a good solution. – Mark Ransom Aug 31 '19 at 17:35
  • If it's really necessary to not read the whole file, I'd start with https://stackoverflow.com/q/232237/5987 – Mark Ransom Aug 31 '19 at 17:37

1 Answers1

0

if you know the exact total line numbers of your .txt file (1000 lines as you said) so use below code (with Pythons built-in linecache.getline()), and if not , first get the total numbers to not get error.

 import linecache 
 filename = "words.txt" 

 line = linecache.getline(filename, 123)     # 123 is a random line number 
 print(line)
Ralf
  • 16,086
  • 4
  • 44
  • 68
Seyfi
  • 1,832
  • 1
  • 20
  • 35
  • This is an interesting option, but I don't know how it is implemented under the hood; maybe it does read the file into memory till it finds the specified line number. – Ralf Aug 31 '19 at 14:55
  • @Ralf, you can read more on https://docs.python.org/3.7/library/linecache.html#module-linecache , But as python documentation expresses, it is **Random access to text lines** that means it reads just one line not all lines then output certain line! – Seyfi Aug 31 '19 at 15:23
  • For a pure text file, given a line number, there is no way a reader can determine where that line starts in the file until it reads to that line. I think what this module does is to incrementally cache that information after each call, allowing faster access in subsequent calls. – GZ0 Aug 31 '19 at 17:18
  • 1
    @GZ0 you're right, after your hint i looked to `linecache` source code: https://github.com/python/cpython/blob/master/Lib/linecache.py . I think `Random Access` that python.org expresses is something out of the box not under the hood. But it is efficient, Look for https://stackoverflow.com/a/19190196/6478645 – Seyfi Sep 01 '19 at 07:45