简体   繁体   English

如何在python中读取文本文件的任意行?

[英]How to read an arbitrary line of a text file in python?

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). 我正在做一个猜单词游戏,我已经创建了一个文本文件,每一行都是一个单词(1000行)。

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. 我进行了快速搜索,每个人都将整个文件读入内存并从那里获取随机行,但是我想读取字符串形式的随机行。

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. 如果您知道.txt文件的确切总行号(如您所说的1000行),请使用下面的代码(带有Pythons内置的linecache.getline() ),否则,请首先获取总号,以免出错。

 import linecache 
 filename = "words.txt" 

 line = linecache.getline(filename, 123)     # 123 is a random line number 
 print(line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM