简体   繁体   English

python seek函数在动态更新的数据上返回空字符串

[英]python seek function return empty string on dynamic updated data

I am using seek function to extract new lines in an updated file. 我正在使用seek函数在更新的文件中提取新行。 My code looks like this: 我的代码如下所示:

read_data=open('path-to-myfile','r')
read_data.seek(0,2)
while True:
     time.sleep(sometime)
     new_data=read_data.readlines()
     do something with new_data

myfile is a csv file that will be constantly updated myfile是一个会不断更新的csv文件

The problem is that usually after several loops inside the while, new_data return nothing. 问题是通常在while内经过几次循环后,new_data不返回任何内容。 It can be different loop numbers. 它可以是不同的循环号。 While I checked myfile, it is still updating..... So any problem I have on my code ? 当我检查myfile时,它仍在更新.....那么我的代码有任何问题吗? Or is there any other way to do this ? 还是有其他方法可以做到这一点?

Any help appreciated !! 任何帮助表示赞赏!

You have two programs accessing the same file on disk? 您有两个程序访问磁盘上的相同文件? If that is the case, then the resource may be locking. 如果真是这样,则资源可能正在锁定。 I set up an example script that writes to a file, and another file that reads for changes based on the code you provided. 我设置了一个示例脚本,该脚本可以写入文件,而另一个文件可以根据您提供的代码读取更改。

So in one instance of python: 因此,在python的一个实例中:

import time
while True:
    time.sleep(2)
    with open('test.txt','a') as read_data:
        read_data.seek(0,2)
        read_data.write("bibbity boopity\n")

And in another instance of python 而在python的另一个实例中

import time
read_data=open('test.txt','r')
read_data.seek(0,2)
while True:
     time.sleep(1)
     new_data=read_data.readlines()
     print(new_data)

In this case, the resource is updating slower than its being read, so changes printed by the bottom prog will be blank. 在这种情况下,资源的更新速度慢于其读取速度,因此底部编排打印的更改将为空白。 But if I speed up the changes per second, well I still see them. 但是,如果我加快每秒的更改速度,那么我仍然会看到它们。 But there are some instances where not all the updates are seen. 但是在某些情况下,并非所有更新都可以看到。

You may want to use asynchronous file reading to catch all the changes. 您可能想使用异步文件读取来捕获所有更改。 Python 3 asyncio library doesn't support async file read/write, but curio does. Python 3 asyncio库不支持异步文件读/写,但是curio支持

See also this question 另请参阅此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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