比较路径/使用pathlib检查最近添加的文件

问题描述 投票:0回答:1

[过去,我使用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')]所以我不能以与oschange = set(after) - set(before)

相同的步骤使用它
python python-3.x
1个回答
0
投票

通过调用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
© www.soinside.com 2019 - 2024. All rights reserved.