首页 > 解决方案 > 如何在 Python3 中使用生成器对象( pathlib.iterdir )进行比较?

问题描述

我在名为调用的目录中有大量文件。所有这些文件的文件名中都包含其创建日期,例如:20181022 _151012_kK029150d6.xml

我需要找到创建日期 >= 180 天的所有文件。我正在使用 pathlib 收集文件名并可以打印文件名。我想做这样的事情:

calls = Path('/Users/muh/Python/calls')
for fyle in calls.iterdir():
    datetime.strptime(fyle[:8], "%Y%m%d")

但我得到“PosixPath' 对象不可下标”

我需要将每个文件名中的 YYYYMMDD 与当前的 YYYYMMDD 进行比较,仅此而已。

标签: pythonpython-3.xpathlib

解决方案


正如@juanpa.arrivillaga建议使用fyle.name[:8]的那样,这很好。

建议:每当您遇到此类问题时,只需尝试按如下方式获取该对象的详细信息(任何对象的定义属性/方法是什么)。

>>> contents = calls.iterdir()
>>> 
>>> content = contents.next()
>>> 
>>> content
PosixPath('/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls/20181022_151012_kK029150d6.xml')
>>> 
>>> dir(content)
['__bytes__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__rdiv__', '__reduce__', '__reduce_ex__', '__repr__', '__rtruediv__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__truediv__', '_accessor', '_cached_cparts', '_cparts', '_drv', '_flavour', '_format_parsed_parts', '_from_parsed_parts', '_from_parts', '_hash', '_init', '_make_child', '_make_child_relpath', '_opener', '_parse_args', '_parts', '_pparts', '_raw_open', '_root', '_str', 'absolute', 'anchor', 'as_posix', 'as_uri', 'chmod', 'cwd', 'drive', 'exists', 'glob', 'group', 'is_absolute', 'is_block_device', 'is_char_device', 'is_dir', 'is_fifo', 'is_file', 'is_reserved', 'is_socket', 'is_symlink', 'iterdir', 'joinpath', 'lchmod', 'lstat', 'match', 'mkdir', 'name', 'open', 'owner', 'parent', 'parents', 'parts', 'relative_to', 'rename', 'replace', 'resolve', 'rglob', 'rmdir', 'root', 'stat', 'stem', 'suffix', 'suffixes', 'symlink_to', 'touch', 'unlink', 'with_name', 'with_suffix']
>>> 

在上面的列表中,您会找到条目,如[..., 'mkdir', 'name', 'open', 'owner', 'parent', ...]您可以看到'name'的部分。所以最后,你可以尝试访问like fyle.name| type(fyle.name)等来检查它是否是一个字符串或其他任何东西。

解决方案:

所以,你可以这样做。

from pathlib import Path
from datetime import datetime

calls = Path("/Users/muh/Python/calls")
details = {}

i = 1
for fyle in calls.iterdir():
    date = datetime.strptime(fyle.name[:8], "%Y%m%d")

    # Write logic here 

详细的:

在下面的代码中,我将详细信息存储到字典中,以便您可以查看代码中更改的对象的不同状态。

在我的例子中,目录的路径calls/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls.

我已经存储了每一点,以帮助您找出问题所在。除了d & details之外,我没有尝试引入新变量,并且出于不同目的多次重复使用名为fyle的变量(如果在简单程序中不再使用该变量很好,引入有意义的变量也很好大型应用程序的变量名)。

date是可用于操作以实现最终目标的实际日期时间对象。

from pathlib import Path
from datetime import datetime

calls = Path("/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls")
details = {}

i = 1
for fyle in calls.iterdir():
    d = {}
    d["pathlib"] = fyle

    fyle = str(fyle)
    d["fullpath"] = fyle

    # fyle = fyle.split("/")[-1]
    fyle = fyle.name[:8]
    d["file_name"] = fyle

    date = datetime.strptime(fyle[:8], "%Y%m%d")
    d["date"] = date

    # Write your business logic here

    details["file" + str(i)] = d
    i += 1

print(details)

输出

{'file2': {'date': datetime.datetime(2018, 10, 25, 0, 0), 'file_name': '20181025_151013_kK029150d7.xml', 'fullpath': '/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls/20181025_151013_kK029150d7.xml', 'pathlib': PosixPath('/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls/20181025_151013_kK029150d7.xml')}, 'file1': {'date': datetime.datetime(2018, 10, 22, 0, 0), 'file_name': '20181022_151012_kK029150d6.xml', 'fullpath': '/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls/20181022_151012_kK029150d6.xml', 'pathlib': PosixPath('/Users/hygull/Projects/django1.9.x-docs/Sfw/file_handling/calls/20181022_151012_kK029150d6.xml')}}

推荐阅读