itertools ChainFromInterables反斜杠规范化?

2024-10-03 21:31:47 发布

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

不久前我发了一个问题:

Writing List To Text File

我能把字典里的文件清单写进一个文本文件里。

所以我的代码是这样的:

simonDuplicates = chain.from_iterable([files for files in file_dict.values() if len(files) > 1])

text_file.write("Duplicates Files:%s" % '\n'.join(simonDuplicates))

这基本上打印出目录和文件,例如:

C:/Users/Simon/Desktop/我的文件.jpg

问题是正斜杠。我希望它们是反斜杠(在Windows中使用)。我试过使用os.path.normpath,但它不起作用

^{pr2}$

我得到以下错误:

Traceback (most recent call last):
  File "duff.py", line 125, in <module>
    os.path.normpath(duplicates)
  File "C:\Python27\lib\ntpath.py", line 402, in normpath
    path = path.replace("/", "\\")
AttributeError: 'itertools.chain' object has no attribute 'replace'

我觉得它没用是因为我应该用iSlice?

Martijn Pieter对这个问题的回答似乎是正确的:

Troubleshooting 'itertools.chain' object has no attribute '__getitem__'

有什么建议吗?


Tags: 文件pathinpychainoslinefiles
1条回答
网友
1楼 · 发布于 2024-10-03 21:31:47

您试图在^{}上应用os.path.normpath, 返回生成器对象。因此,您必须迭代直到生成器耗尽,以获得字符串类型的文件名的完整列表。在

你可以像这样使用列表理解

simonDuplicates = [os.path.normpath(path) for path in chain.from_iterable(files for files in file_dict.values() if len(files) > 1)]

或者您可以像这样使用map函数

^{pr2}$

相关问题 更多 >