简体   繁体   中英

Read two lines at a time from a txt file

I would like to make a twitter bot that opens a txt file, read two lines and publish them, then sleeps for some time and publish the next 2 lines

I tried it with reading one line and it's working. It reads one line at a time and publishes it, but I still can't figure out a way to make it read two lines at once. 8 days experience with Python 🤭.

It publishes one line at a time

file = open('textfile.txt', 'r')
filelines = file.readlines()
file.close()

for line in filelines:
    if line != '\n':
        api.update_status(line)
...

not original .

you can iterate over the file using enumerate to get line numbers, and simply store even number lines in a temp variable, and move on to the next odd number line. On odd number lines you can then have access to the previous line as well as the current line.

with open('somefile.txt', 'r') as f:
    lastline = ''
    for line_no, line in enumerate(f):
        if line_no % 2 == 0: #even number lines (0, 2, 4 ...) go to `lastline`
            lastline = line
            continue #jump back to the loop for the next line
        print("here's two lines for ya")
        print(lastline)
        print(line)

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