[英]Using readline() to read a full line then move onto the next one in .txt file with each subsequent run using Python
I am relatively new to Python, but after reading a lot of posts about using readline() and readlines(), I can't seem to figure this one out.我对 Python 比较陌生,但是在阅读了很多关于使用 readline() 和 readlines() 的帖子之后,我似乎无法弄清楚这一点。
quotes = open("quotes.txt", "r")
#Opens the quotes file
quote = quotes.readlines()
#Uses the readlines() method to read each line of text file
lineCount = 0
for line in quote:
lineCount += 1
print("{}".format(line.strip()))
So, here I am using the readlines() method, but the problem is, this code prints every line at once.所以,我在这里使用 readlines() 方法,但问题是,这段代码一次打印每一行。
So then I tried readline() in the code, but then the coded only prints one line, I won't show the code for this because I had no luck figuring it out.所以我在代码中尝试了 readline() ,但是编码只打印了一行,我不会显示这个代码,因为我没有运气弄清楚它。
I'm looking to print a line, increment a counter and break.我正在寻找打印一行,增加一个计数器并中断。
Then on the next run of code, it prints the next line and breaks.然后在下一次代码运行时,它会打印下一行并中断。
So, in essence:所以,本质上:
When I run my program the first time it would print:当我第一次运行我的程序时,它会打印:
"Quote 1" - Author
Then, on the next run it would be:然后,在下一次运行中,它将是:
"Quote 2" - Author
Anyone who can help figure this out for me, it would be greatly appreciated.任何可以帮助我解决这个问题的人,将不胜感激。
Thanks!谢谢!
Additional information:附加信息:
I have compiled a list of quotes from an old podcast which is written line by line in the quotes.txt file, this is for a Twitter bot that I am currently developing using the Tweepy module.我已经从一个旧的播客中编译了一个引用列表,该列表在quotes.txt 文件中逐行写入,这是针对我目前正在使用 Tweepy 模块开发的 Twitter 机器人。 For now, I have collected a large number of quotes so I am not currently worried about the program looping back around and starting again until I get closer to that time.
目前,我已经收集了大量的报价,所以我目前并不担心程序会循环回来并重新开始,直到我接近那个时间。
Thanks all for the help already.谢谢大家的帮助。
In order to know which line to read on the next script execution, we need to save this information permanently.为了知道在下一个脚本执行时读取哪一行,我们需要永久保存这些信息。 To do so, you could write the line counter to a text file and read its contents upon startup.
为此,您可以将行计数器写入文本文件并在启动时读取其内容。 However, there might be a problem on the very first script execution: If the script was never run before, there is no file saved.
但是,在第一次执行脚本时可能会出现问题:如果之前从未运行过该脚本,则没有保存文件。 Reading from a non-exisitng file would raise an error.
从不存在的文件中读取会引发错误。 Therefore we
try
to read from SAVE_FILE
.因此我们
try
从SAVE_FILE
中读取。 If the file is available, we use the saved number.如果文件可用,我们使用保存的号码。 If it is not available we initilize the line number by defining
line_number_to_show = 0
.如果它不可用,我们通过定义
line_number_to_show = 0
来初始化行号。 We then open the file containing the quotes, iterate over the line numbers and look for the line number we are interested in. If the specified line is found, we print it.然后我们打开包含引号的文件,遍历行号并查找我们感兴趣的行号。如果找到指定的行,我们打印它。 The next step is to save the line number for the next program execution.
下一步是保存下一个程序执行的行号。
A very basic approach would look like this:一个非常基本的方法如下所示:
SAVE_FILE = 'line_number.txt'
try:
with open(SAVE_FILE) as save_file:
line_number_to_show = save_file.read().strip()
line_number_to_show = int(line_number_to_show)
except (FileNotFoundError, ValueError) as _:
line_number_to_show = 0
with open("quotes.txt") as quotes_file:
for line_number, line in enumerate(quotes_file):
if line_number == line_number_to_show:
print(line)
with open(SAVE_FILE, 'w') as save_file:
line_number_to_show = line_number_to_show + 1
save_file.write(f'{line_number_to_show}')
Important notes:重要笔记:
SAVE_FILE
the way I did is error prone as we do not perform any sanity checks or catch possible errors in try/except blocks.SAVE_FILE
读取行号很容易出错,因为我们不执行任何健全性检查或捕获 try/except 块中可能出现的错误。 Production code would require further countermeasures to deal with these issues..readlines()
to read the complete file contents into a list..readlines()
将完整的文件内容读入列表,而不是像我那样读取文件。 As the list is stored in memory and the complete file is read, this might lead to high memory consumption when dealing with huge files.enumerate()
reads the file chunk-wise and is considered to be more memory efficient .enumerate()
执行它会逐块读取文件,并且被认为是更高效的 memory 。Just use:只需使用:
f = open("quotes.txt","r")
lineCount = 0
for i in range(4):
lineCount+=1
print(f.readline())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.