简体   繁体   中英

Reading from a .txt file dynamically with Python

I have a text file that will be populated depending on a radio button selected by a user in php

I am reading from the same text file, whenever I find that a new line has been added the Python script prints it. For now I am just printing it. Eventually I will send out a message on a GSM modem based on the new records in the .txt file. Right now I'm just printing it to make sure I can identify a new record.

Here's the code I'm using. It works just fine.

def main():
    flag = 0
    count = 0
    while flag == 0:
        f = open('test.txt', 'r')
        with open('test.txt') as f:
            for i, l in enumerate(f):
                pass
        nol = i + 1
        if count < nol:
            while count <= nol:
                f = open('test.txt', 'r')
                a = f.readlines(count)
                if count == 0:
                    print a[0]
                    count = count+2
                else:
                    print a[count-1]
                    count = count+1
if __name__ ==  '__main__':
    main()

I was wondering if there is a better way to do this.

Also, php will keep writing to the file. And python will keep reading from it. Will this cause a clash? Since multiple instance are open?

According to this answer you can use watchdog package to watch over changes in the file. Alternatively you can use custom made solution using fcntl in Unix.

First solution has advantage of being cross-platform.

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