【问题标题】:Is there a way to loop through a list, and assign a variable有没有办法遍历一个列表,并分配一个变量
【发布时间】:2021-03-23 06:53:26
【问题描述】:

我想做的是将变量 (a) 分配给 (b) 的每个实例。 (a) 中有 30 个文件夹,应如下所示: 'm:/groupfolder/susan/01' 'm:/groupfolder/susan/03' 'm:/groupfolder/susan/04' ...

这就是我正在做的 -

import os
from os import listdir
a = ('m:/groupfolder/susan')
b = []
for x in os.listdir(a):
   b.append(x)

fha = [b]
for y in fha:
    path = a+b
 Error mesage = "TypeError: can only concatenate str (not "list") to str"

请让我知道我做错了什么 - 是的,我对 Python 还比较陌生,还在学习。 谢谢

【问题讨论】:

  • fha 是一个列表列表。不是字符串列表。

标签: python list append typeerror


【解决方案1】:

而不是收集列表中的所有文件名然后再次迭代它。您只需一步即可完成:

import os                                                                                                                                                              

b = []                                                                                                                                                                 
for file in os.listdir(s): 
    print(file) 
    b.append(s+'/'+file) 

print(b) 

【讨论】:

    【解决方案2】:

    使用列表推导获取完整文件路径的列表:

    import os
    file_paths = [os.path.abspath(f) for f in os.listdir('dir_name')]
    print(file_paths)
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 2013-05-07
      • 2016-01-16
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多