-1

在 os.walk 函数的结果中,我得到了这个列表,其中包含文件夹中的文件名:

['tr-02-10-18.pdf', 'tr-02-11-18.pdf', 'tr-02-12-18.pdf', 'tr-03-11-18.pdf', 'tr-03-12-18.pdf', 'tr-04-10-18.pdf', 'tr-04-11-18.pdf', 'tr-04-12-18.pdf']

我的目标是将列表带到该表单:

['tr/02/10/18.pdf', 'tr/02/11/18.pdf','tr/02/12/18.pdf', 'tr/03/11/18.pdf', 'tr/03/12/18.pdf', 'tr/04/10/18.pdf', 'tr/04/11/18.pdf', 'tr/04/12/18.pdf']

我尝试使用如下所示的代码:

import os
for file_name in os.walk(input()):
    egg1=(str(file_name[-1]))
    egg2= []
    for mark in egg1:
        mark=[i.replace("-","/") for i in mark]
        egg2.append(mark)
print(egg2)

我得到的是这个列表:

[['['], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['0'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['2'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['3'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['3'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['0'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['1'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [','], [' '], ["'"], ['t'], ['r'], ['/'], ['0'], ['4'], ['/'], ['1'], ['2'], ['/'], ['1'], ['8'], ['.'], ['p'], ['d'], ['f'], ["'"], [']']]

PS这是我的第一个问题,如有不一致之处请见谅

4

1 回答 1

1

你犯了几个错误:

  1. os.walk()生成一个包含 3 个元素的元组,即当前目录的路径、文件名列表和目录名列表。您将元组命名为file_name

    for file_name in os.walk(input()):
    

    最好将其拆分为单独的组件,因此for dirpath, dirnames, filenames in os.walk(...):. 由于您忽略了前两个参数,因此您也可以使用for *_, filenames in os.walk(...):

  2. 您将文件名列表转换为单个字符串:

    egg1=(str(file_name[-1]))
    

    file_name[-1]是文件名列表。你把列表变成了一个字符串,所以现在你有了字符串表示和[,],逗号字符:

    >>> egg1
    "['tr-02-10-18.pdf', 'tr-02-11-18.pdf', 'tr-02-12-18.pdf', 'tr-03-11-18.pdf', 'tr-03-12-18.pdf', 'tr-04-10-18.pdf', 'tr-04-11-18.pdf', 'tr-04-12-18.pdf']"
    

    然后,您从上面的字符串中取出每个单独的字符,并用斜杠替换破折号。不要将列表变成字符串,直接遍历列表。

  3. 您将列表替换egg2为每个目录的新的空列表。在循环之前创建列表。os.walk()

  4. 您将每次str.replace()调用的结果放入一个包含单个元素的新列表中,然后将该列表附加到egg2列表中。不要添加更多列表。

此代码有效:

result = []

for *_, filenames in os.walk(input()):
    for filename in filenames:
        replaced = filename.replace('-', '/')
        result.append(replaced)

这可以组合成一个列表理解:

result = [f.replace('-', '/') for *_, fs in os.walk(input()) for f in fs]
于 2019-08-26T13:13:17.083 回答