【无标题】

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了,

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值