0

您好,目前我正在研究 python,我想知道如果 txtfile 不断发生变化,您如何拥有一个正在附加的列表。措辞很困难,无论如何都是代码

list=[]
random_number=0
file_handler=open("history.txt","w")
file_handler.write(str(list))
lenght_cumulative_data=len(list)
confirmed.append(random_number)

现在我想要完成的是数字 0 的列表变量将显示在 history.txt 中,但这不会发生,让我们想象一下 random_number 总是在变化我希望列表变量能够始终更新自己。就像假设 random_number 更改为 1 然后 2 我希望列表更新为 [0,1,2]。你是怎样做的?我一直在 youtube 上搜索,他们给我的只是这个写功能,无论如何有人可以参考它或有什么想法吗?

4

2 回答 2

0

注意:此答案仅适用于 Windows

changes.py

# Adapted from http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html

import threading
import os

import win32file
import win32con

ACTIONS = {
    1 : "Created",
    2 : "Deleted",
    3 : "Updated",
    4 : "Renamed from something",
    5 : "Renamed to something"
}
# Thanks to Claudio Grondi for the correct set of numbers
FILE_LIST_DIRECTORY = 0x0001

def monitor_changes(callback, path, filenames):
    path = path or ""
    if type(filenames) == "str":
        filenames = (filenames,)

    thread = threading.Thread(target=_monitor, args=(callback, path, filenames))
    thread.start()

    return thread

def _monitor(callback, path, filenames):
    hDir = win32file.CreateFile (
        path,
        FILE_LIST_DIRECTORY,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
        None,
        win32con.OPEN_EXISTING,
        win32con.FILE_FLAG_BACKUP_SEMANTICS,
        None
    )
    while True:
        #
        # ReadDirectoryChangesW takes a previously-created
        # handle to a directory, a buffer size for results,
        # a flag to indicate whether to watch subtrees and
        # a filter of what changes to notify.
        #
        # NB Tim Juchcinski reports that he needed to up
        # the buffer size to be sure of picking up all
        # events when a large number of files were
        # deleted at once.
        #
        results = win32file.ReadDirectoryChangesW (
            hDir,
            1024,
            True,
            win32con.FILE_NOTIFY_CHANGE_LAST_WRITE,
            None,
            None
        )

        for action, file in results:
            if filenames and file not in filenames and os.path.basename(file) not in filenames:
                continue
            callback(action, file)

if __name__ == '__main__':
    # monitor by printing
    t = monitor_changes(print, ".", None)

在你的main.py

import changes
import os

my_list = []

def callback(action_id, filename):
    # the function running means
    # that the file has been modified
    
    action_desc = changes.ACTIONS[action_id]
    print(action_desc, filename)

    with open(filename) as f:
        my_list.append(f.read())

thread = changes.monitor_changes(callback, ".", "my_file_that_I_want_to_monitor.txt")

如果要监视目录中的所有文件,请调用monitor_changeswithNone作为第三个参数。

注意:这将监视所有子目录,因此具有相同名称但在不同文件夹中的文件将触发回调。如果您想避免这种情况,请检查传递给回调函数的文件名是否正是您想要监控的。

于 2020-08-26T13:31:56.533 回答
0
from os import stat
from _thread import start_new_thread
from time import sleep

List = []

class WatchFileForChanges:
    def __init__(self, filename):
        self.file = filename
        self.cached_file = stat(self.file).st_mtime

    def watch(self):
        num = 0
        while 1:
            status = stat(self.file).st_mtime
            if status != self.cached_file:
                self.cached_file = status
                #file changed
                List.append(num)
                num += 1

def main():

    Watcher = WatchFileForChanges("file.txt")

    start_new_thread(Watcher.watch, ())

    while 1:
        print(List)
        sleep(1)


if __name__ == '__main__':
    main()

这将做你想要的。如果我理解正确,您希望在每次文件更改时附加到列表中。

于 2020-08-26T12:04:07.843 回答