Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python——读取文件,保存文件名并访问这些文件_Python - Fatal编程技术网

Python——读取文件,保存文件名并访问这些文件

Python——读取文件,保存文件名并访问这些文件,python,Python,我建造 并通过以下方式从文件夹A、B、C、D中提取文件名: totalset = {} 现在我想构建一个名为namelist的东西,它包含所有文件名,我可以通过以下方式遍历文件夹中的所有文件: for file_name in (os.listdir(full_subdir_name)): full_file_name = os.path.join(full_subdir_name, file_name) 我该怎么办?您可能应该使用“列表理解”。下面是一个示例,说明了如何做到这一点

我建造

并通过以下方式从文件夹A、B、C、D中提取文件名:

totalset = {} 
现在我想构建一个名为namelist的东西,它包含所有文件名,我可以通过以下方式遍历文件夹中的所有文件:

for file_name in (os.listdir(full_subdir_name)):
    full_file_name = os.path.join(full_subdir_name, file_name)
我该怎么办?

您可能应该使用“列表理解”。下面是一个示例,说明了如何做到这一点:

for file in namelist[A]:
    blabla...

for file in namelist[B]:
    blabla.. .  
然后您将构建完整的
名称列表
类似的内容。首先,你应该建立一个名字列表

lst_names = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]
一旦您用自己的姓名设置了
lst_名称
,请构建完整的
名称列表

# example using Windwows filenames
# note that we use "raw strings" with r'' so the backslash will not be weird
lst_names = [r'C:\Users\steveha\Desktop', r'C:\Users\steveha\Documents', r'C:\Users\steveha\Music']

# example using Mac or Linux filenames
lst_names = ['/home/steveha/Desktop', '/home/steveha/Documents', '/home/steveha/Music'
就我个人而言,我认为使用较短的变量名比使用
full\u subdir\u name
更容易阅读:

namelist = {}

for full_subdir_name in lst_names:
    namelist[full_subdir_name] = [os.path.join(full_subdir_name, n) for n in os.listdir(full_subdir_name)]

那么我应该如何遍历lst\u name呢?我添加了一些设置
lst\u name
的示例。这说明问题了吗?如果您事先不知道名称列表,并且希望扫描文件系统,则可能需要使用
os.path.walk()
namelist = {}

for f in lst_names:
    namelist[f] = [os.path.join(f, n) for n in os.listdir(f)]