简体   繁体   中英

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.

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.

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.

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. 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 . 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 . 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. 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. 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. Doing it via enumerate() reads the file chunk-wise and is considered to be more memory efficient .
  • 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. 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.

Just use:

f = open("quotes.txt","r")
lineCount = 0
for i in range(4):
    lineCount+=1
    print(f.readline())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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