[过去,我使用os
进行监视并使用新文件。现在,我尝试使用pathlib
并替换os
。有没有这么简单的方法来比较文件夹并检查添加的文件?
这里是os
的示例:
before = os.listdir(downPath)
# <..doing stuff like downloading a file..>
after = os.listdir(downPath)
change = set(after) - set(before)
if len(change) == 1:
file_name = change.pop()
print("New File:", file_name)
print("Renaming")
os.rename(file_name, basenew)
else:
print("ERROR: More than one file or no file downloaded")
我尝试使用
cwd = Path.cwd()
before = list(Path(cwd).rglob('*'))
print(before)
# ... and so on like above
但是list
返回一个或多个path
元素,如下所示:[PosixPath('/home/user/example.txt')]
所以我不能以与os
(change = set(after) - set(before)
)
通过调用PosixPath
方法获得PosixPath.as_posix()
对象的数组后,只需增加一个步骤,就可以得到以前得到的内容。这将从文档返回Return the string representation of the path with forward (/)
。然后在路径上调用os.basename
,您将回到使用os.listdir()
的位置。
>>> cwd = Path.cwd()
>>> before = list(Path(cwd).rglob('*'))
>>> # Overwrite before with
>>> before = [os.path.basename(file_.as_posix()) for file_ in before]
>>> # Proceed as done before and do the same for after list