如何迭代并从Python fcache中删除某些文件?

2024-05-19 22:47:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的PyQt5应用程序中,我一直在使用fache(https://pypi.org/project/fcache/)将大量小文件缓存到用户的temp文件夹中以提高速度。它在缓存方面工作得很好,但是现在我需要能够遍历缓存文件并有选择地删除不再需要的文件

但是,当我尝试遍历FileCache对象时,我得到了一个错误

thisCache是我的缓存的名称,如果我print(thisCache)得到: 这很好

如果我做print(thisCache.keys()),我得到KeysView(<fcache.cache.FileCache object at 0x000001F7BA0F2848>),这似乎是正确的(我想?)。类似地,printing.values()提供了一个ValuesView

如果我做print(len(thisCache.keys()),我会得到:1903,显示其中有1903个文件,这可能是正确的。但这就是我被困住的地方

如果我尝试以任何方式遍历KeysView,就会得到一个错误。以下每次尝试: for f in thisCache.values():for f in thisCache.keys(): 总是抛出错误: Process finished with exit code -1073740791 (0xC0000409)

我对Python还相当陌生,所以我是不是误解了应该如何遍历这个列表?或者这里有我需要解决的问题

谢谢

:::::::::::::::::::::

经过一段时间的延迟后,这里有一个可复制的(但不是特别小的或高质量的)示例代码

import random
import string
from fcache.cache import FileCache
from shutil import copyfile

def random_string(stringLength=10):
    letters = string.ascii_lowercase
    return ''.join(random.choice(letters) for i in range(stringLength))

cacheName = "TestCache"
cache = FileCache(cacheName)

sourceFile = "C:\\TestFile.mov"
targetCount = 50

# copy the file 50 times:
for w in range(1, targetCount+1):
    fileName = random_string(50) + ".mov"
    targetPath = cache.cache_dir + "\\" + fileName
    print("Copying file ", w)
    copyfile(sourceFile, targetPath)
    cache[str(w)] = targetPath
print("Cached", targetCount, "items.")

print("Syncing cache...")
cache.sync()

# iterate through the cache:
print("Item keys:", cache.keys())
for key in cache.keys():
    v = cache[key]
    print(key, v)

print("Cache read.")

有一个依赖关系,在您的系统上有一个名为“C:\TestFile.mov”的文件,但是路径并不重要,因此可以指向任何文件。我用其他文件格式进行了测试,得到了相同的结果

引发的错误是:

回溯(最近一次呼叫): 文件“C:\Users\stuart.bruce\AppData\Local\Programs\Python37\lib\encodings\hex\u codec.py”,第19行,十六进制解码 返回(binascii.a2b\u hex(输入),len(输入)) binascii。错误:找到非十六进制数字

上述异常是以下异常的直接原因:

Traceback (most recent call last):
  File 
"C:\Users\stuart.bruce\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "C:\Users\stuart.bruce\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\stuart.bruce\PycharmProjects\testproject\test_code.py", line 32, in <module>
    for key in cache.keys():
  File "C:\Users\stuart.bruce\AppData\Local\Programs\Python\Python37\lib\_collections_abc.py", line 720, in __iter__
    yield from self._mapping
  File "C:\Users\stuart.bruce\AppData\Local\Programs\Python\Python37\lib\site-packages\fcache\cache.py", line 297, in __iter__
    yield self._decode_key(key)
  File "C:\Users\stuart.bruce\AppData\Local\Programs\Python\Python37\lib\site-packages\fcache\cache.py", line 211, in _decode_key
    bkey = codecs.decode(key.encode(self._keyencoding), 'hex_codec')
binascii.Error: decoding with 'hex_codec' codec failed (Error: Non-hexadecimal digit found)

test_code.py的第32行(如错误中所述)是第for key in cache.keys():行,因此这里似乎找到了一个非十六进制字符。但首先我不知道为什么,其次我不知道该怎么处理

(另外,请注意,如果您运行此代码,您将在临时文件夹中找到所选文件的50个副本,并且没有任何东西会自动整理它!)


Tags: 文件keyinpycacheforlocal错误
1条回答
网友
1楼 · 发布于 2024-05-19 22:47:28

在读取fcache的源代码之后,cache_dir似乎只能由fcache本身使用,因为它读取所有文件以查找先前创建的缓存数据

程序(或者更好地说,模块)崩溃是因为您在该目录中创建了其他文件,而它无法处理这些文件

解决方案是使用另一个目录来存储这些文件

import os

# ...

data_dir = os.path.join(os.path.dirname(cache.cache_dir), 'data')
if not os.path.exists(data_dir):
    os.mkdir(data_dir)
for w in range(1, targetCount+1):
    fileName = random_string(50) + ".mov"
    targetPath = os.path.join(data_dir, fileName)
    copyfile(sourceFile, targetPath)
    cache[str(w)] = targetPath

相关问题 更多 >