如何解决将追加列表更新为txt文件
您好,我目前正在研究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上搜索,他们给我的就是这个写功能,无论如何有人可以推荐它或有任何想法吗?
解决方法
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()
这将做您想要的。 如果我对您的理解正确,那么您希望每次文件更改时都将其添加到列表中。
,注意:此答案仅适用于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,filenames))
thread.start()
return thread
def _monitor(callback,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
)
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_changes
作为第三个参数调用None
。
注意:这将监视所有子目录,因此具有相同名称但位于不同文件夹中的文件将触发回调。如果要避免这种情况,请检查传递给回调函数的文件名是否确实要监视。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。