问题描述
如果该路径尚不存在,我正在尝试将jpg文件路径附加到预先存在的文本列表中。我还试图将列表像字节一样处理,以提高效率。
#----> Variables
jpg_index = "/path/to/list_of_jpgs"
search_locations = ["path/to/folder/a","path/to/folder/b"]
#---> Code
#does my path exist
if os.path.exists(jpg_index):
#for-loop to check all given search locations
for search_location in search_locations:
#find paths ending with jpg
for path in Path(search_location).rglob('*.jpg'):
#Open the index file / jpg list and append paths
with open(jpg_index,'a') as filehandle:
filehandle.writelines('%s\n' % path)
但是,当我尝试检查预先存在的文本以查看是否应添加新路径时,似乎什么也没发生。我正在尝试以下变化:
#----> Variables
jpg_index = "/path/to/list_of_jpgs"
search_locations = ["path/to/folder/a","path/to/folder/b"]
#---> Code
#does my path exist
if os.path.exists(jpg_index):
#for-loop to check all given search locations
for search_location in search_locations:
#find paths ending with jpg
for path in Path(search_location).rglob('*.jpg'):
#Open the jpg_index so it can be scanned for matches
with open(jpg_index,'rb',0) as file,\
mmap.mmap(file.fileno(),access=mmap.ACCESS_READ) as s:
#proceed if no matches are found
if s.find(b'path') != -1:
#Open the index file / jpg list and append paths
with open(jpg_index,'a') as filehandle:
filehandle.writelines('%s\n' % path)
我尝试了其他各种解决方案,例如改组,使用mmap
开始检查,尝试避免两次使用with open
,而且我确信它不是在检查字符串'path'看着我的路径。
但是,我经常没有收到错误消息,因此很难继续前进。显然它正在工作,但不是我想要的。
#---> Modules (c&p from top of code)
import os
import pathlib
import glob,os
from pathlib import Path
import os.path
from os import path
import mmap
编辑:
我还尝试实现@skywallkee给出的答案,并将代码更改为:
if os.path.exists(jpg_index):
for search_location in search_locations:
for path in Path(search_location).rglob('*.jpg'):
mmap.mmap(file.fileno(),access=mmap.ACCESS_READ) as s:
if s.find(str.encode(path.__str__())) < 0:
with open(jpg_index,'a') as filehandle:
filehandle.writelines('%s\n' % path)
但是,这会导致错误
mmap.mmap(file.fileno(),access=mmap.ACCESS_READ) as s:
^
SyntaxError: invalid Syntax
我在哪里错了? (我在Mac上,将Atom与Hydrogen模块一起使用。)
编辑2:
我删除了太多内容,skywallkee的解释很好,请参见他的Pastebin,他的解决方案没有我的错误。
请注意,使用Atom似乎失败,因为如果在选项卡中打开该列表,则该列表不会扩展。文本列表必须关闭并重新打开才能观察进度。
解决方法
这是因为您的代码将始终检查文件中是否表示了以字节表示的“路径”,而路径可能根本没有。如果要检查变量路径的内容是否在文件中,则可以执行以下操作:
if s.find(str.encode(path.__str__())) < 0:
#Open the index file / jpg list and append paths
with open(jpg_index,'a') as filehandle:
filehandle.writelines('%s\n' % path)
如果找到文件,s.find将给出一个正值,因此您要检查它是否小于0,以便可以写入文件。如果您要检查它是否为!= -1,那么您很可能永远不会写入文件,因为s.find会返回-1,因为找不到文件,而您正在查看s.find!= -1,两者没有什么不同,因此,如果您再也没有涉及。只有在文件中已经有一些路径并且路径已经存在的情况下,您才会进入该路径,这就是为什么您实际上要两次写入路径而从不写入文件中尚未存在的路径的原因。
通过使用str.encode("string")
将字符串转换为字节,因此实际上可以通过执行str.encode(path.__str__())
将路径转换为字节。您还需要调用path。 str (),因为path是WindowsPath(如果在Windows上运行),因此您希望将路径作为字符串。