python 列举当前目录下的所有文件路径
import os
def list_all_files_in_directory(path):
for file_name in os.listdir(path):
file_path = os.path.join(path, file_name)
if os.path.isfile(file_path):
print(file_path)
elif os.path.isdir(file_path):
list_all_files_in_directory(file_path)
list_all_files_in_directory(‘/path/to/folder’)
In this code, replace /path/to/folder with the actual path of the directory you want to list the files in. The os.listdir(path) function is used to get a list of all items (files and directories) in the directory specified by path . The os.path.join(path, file_name) function is used to get the full path of each item. The os.path.isfile(file_path) function is used to check if the item is a file. If it is a file, its path is printed using print(file_path) . If the item is a directory, the function calls itself recursively to list the files in that directory.
目录下有目录 ,调用函数循环列举,结果如下,此处列举目录为 \10.98.23.100\erp,
\10.98.23.100\erp\o237414576.txt
\10.98.23.100\erp\o237414773.txt
\10.98.23.100\erp\o237415012.txt
\10.98.23.100\erp\o237415498.txt
\10.98.23.100\erp\o237415708.txt
\10.98.23.100\erp\o237415925.txt
\10.98.23.100\erp\新建文件夹\新建文本文档.txt
另外 此处是网路路径,本地路径可加r’path’,路径自动加前缀\,网络可不加,
如实现当前目录,不列举子目录,换一下代码
def list_all_files_in_directory(path):
for file_name in os.listdir(path):
file_path = os.path.join(path, file_name)
if os.path.isfile(file_path):
print(file_path)
return
list_all_files_in_directory(file_path)
结果如下,
\10.98.23.100\erp\o237414576.txt
\10.98.23.100\erp\o237414773.txt
\10.98.23.100\erp\o237415012.txt
\10.98.23.100\erp\o237415498.txt
\10.98.23.100\erp\o237415708.txt
\10.98.23.100\erp\o237415925.txt
注意,return 与for对齐,否则有可能只循环显示一个文件路径,因为循环一次就return了,