简体   繁体   English

使用 readline() 读取整行,然后使用 Python 移动到下一个 in.txt 文件,每次后续运行

[英]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 .因此我们trySAVE_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:重要笔记:

  • Reading the line number from the 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.生产代码需要进一步的对策来处理这些问题。
  • Instead of reading the the file the way I did, you could use .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.由于列表存储在 memory 并读取完整文件,这可能会导致处理大文件时的 memory 消耗高。 Doing it via enumerate() reads the file chunk-wise and is considered to be more memory efficient .通过enumerate()执行它会逐块读取文件,并且被认为是更高效的 memory
  • For scaling applications and depending on your infrastructure/architecture (as you said something about a Bot in one of your comments) you might consider using a database to store and read the quotes from.对于扩展应用程序并取决于您的基础架构/架构(正如您在其中一个评论中所说的有关 Bot 的内容),您可能会考虑使用数据库来存储和读取引用。 If doing so, you would also store the required information about which quote to deliver upon the next request.如果这样做,您还将存储有关在下一次请求时提供哪个报价的所需信息。 However, approaching this would be part of several other design decisions and (SO) questions.然而,解决这个问题将是其他几个设计决策和(SO)问题的一部分。

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.

相关问题 在python中使用readline()读取txt文件,但在aws comprehend api中未读取第二行 - using readline() in python to read a txt file but the second line is not read in aws comprehend api 在python中使用readline为正在读取的输入文件的每个单词打印出自己的行 - using readline in python to print out own line for each word of an input file that is being read 使用python读取txt文件的每一行并将其部分分成csv文件 - read each line of a txt file and section parts out into a csv file using python 如何使用 tkinter (Python) 逐行读取变量.txt 文件 - How to read variables with tkinter (Python) using a line by line .txt file 使用readline读取txt文件python3 - Use readline to read txt file python3 使用Python在.txt文件的每一行中附加特定字符串 - Append in each line of a .txt file a specific string using Python 使用 Python 在 a.txt 文件的每一行中添加“-”号 - Adding a “-” sign in each line of a .txt file using Python 一次读取行而不用.readline()将其删除 - Read line once without removing it Python using .readline() 忽略使用file.readline(size)之后读取的其余行 - Ignore the rest of the line read after using file.readline(size) 使用python为txt的每一行添加前缀和后缀 - prefix and suffix to each line of a txt using python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM