# 遍历文件 方法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