python指定文件目录遍历方法

# 遍历文件 方法1:​
import os
path="C:\Users\ROBERTKUN\Desktop\python"
for root,dirs,files in os.walk(path):
    for f in files:
        print(root,f)
        
"""
输出结果<中文有乱码>:
('C:\\Users\\ROBERTKUN\\Desktop\\python', 'ajames.txt')
('C:\\Users\\ROBERTKUN\\Desktop\\python', 'cjames.txt')
('C:\\Users\\ROBERTKUN\\Desktop\\python', 'james.txt')
('C:\\Users\\ROBERTKUN\\Desktop\\python', "python\xd6\xd0xrange\xba\xcdrange\xb5\xc4\xd2\xec\xcd\xac @ CiNiao's blog.htm")
('C:\\Users\\ROBERTKUN\\Desktop\\python', 'python\xb5\xb1\xd6\xd0\xb5\xc4eval\xa3\xa8\xa3\xa9\xba\xaf\xca\xfd\xca\xc7\xc6\xf0\xca\xb2\xc3\xb4\xd7\xf7\xd2\xb5\xb5\xc4\xa3\xbf_\xb0\xd9\xb6\xc8\xd6\xaa\xb5\xc0.htm')
('C:\\Users\\ROBERTKUN\\Desktop\\python', 'python\xce\xc4\xbc\xfe\xb2\xd9\xd7\xf7\xa3\xa8\xb1\xe9\xc0\xfa\xcb\xf9\xd3\xd0\xce\xc4\xbc\xfe\xa3\xa9 - liziyun537\xb5\xc4\xd7\xa8\xc0\xb8 - \xb2\xa9\xbf\xcd\xc6\xb5\xb5\xc0 - CSDN.NET.htm')
"""

# 遍历文件 方法2:
import os


def walkdir(dirName):
    try:
        ls = os.listdir(dirName)
    except:
        print "access deny"
    else:
        for fn in ls:
            temp = os.path.join(dirName, fn)
#如果是文件夹, 则递归调用
            if(os.path.isdir(temp)):
                print(temp)
                walkdir(temp)
            else:
                print(temp)
                
path="C:\Users\ROBERTKUN\Desktop\python"
walkdir(path)


"""
输出结果:
C:\Users\ROBERTKUN\Desktop\python\ajames.txt
C:\Users\ROBERTKUN\Desktop\python\cjames.txt
C:\Users\ROBERTKUN\Desktop\python\james.txt
C:\Users\ROBERTKUN\Desktop\python\python中xrange和range的异同 @ CiNiao's blog.htm
C:\Users\ROBERTKUN\Desktop\python\python当中的eval()函数是起什么作业的?_百度知道.htm
C:\Users\ROBERTKUN\Desktop\python\python文件操作(遍历所有文件) - liziyun537的专栏 - 博客频道 - CSDN.NET.htm
"""
​
问题求助: http://bbs.csdn.net/topics/390540092?page=1#post-395236423
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值