赞
踩
python的标准库有很多,还有第三方库,多的都学不过来了,千里之行始于足下,每周学两到三个模块,慢慢的就掌握的多了,学习的过程中做一下笔记,或许能给想学习相关模块的人以一些帮助......
1、遍历文件夹(os.walk)
文件夹(C:\Users\Desktop\Python)描述:
该文件夹下包含一个文件夹(标准库)和一个文件(Python核心编程(第二版).pdf)
文件夹(标准库)下包含一个文件(51CTO下载-python标准库.pdf)
代码:
- import os
- directory = "C:\Users\Desktop\Python"
- for parent,dirnames,filenames in os.walk(directory):
- print parent
- for dirname in dirnames:
- print dirname
- print os.path.join(parent,dirname)
- for filename in filenames:
- print filename
- print os.path.join(parent,filename)
- C:\Users\Desktop\Python
- 标准库
- C:\Users\Desktop\Python\标准库
- Python核心编程(第二版).pdf
- C:\Users\Desktop\Python\Python核心编程(第二版).pdf
- C:\Users\Desktop\Python\标准库
- 51CTO下载-python标准库.pdf
- C:\Users\Desktop\Python\标准库\51CTO下载-python标准库.pdf
- import os
- directory = "C:\Users\Desktop\Python"
- for parent,dirnames,filenames in os.walk(directory):
- file1 = parent
- for dirname in dirnames:
- file2 = os.path.join(parent,dirname)
- for filename in filenames:
- file3 = os.path.join(parent,filename)
- files = []
- files.extend([file1,file2,file3])
- for File in files:
- print File,"-->",
- if os.path.isabs(File):
- print "isabs",
- if os.path.isdir(File):
- print "isdir",
- if os.path.isfile(File):
- print "isfile",
- if os.path.exists(File):
- print "exists"
- break
- C:\Users\Desktop\Python --> isabs isdir exists
- C:\Users\Python\标准库 --> isabs isdir exists
- C:\Users\Desktop\Python\Python核心编程(第二版).pdf --> isabs isfile exists
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。