Python 常用函数: 文件类操作

Part I: OS模块

Python os模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。(一语中的)

1.1 常用方法

1、os.name

输出字符串指示正在使用的平台。如果是window 则用'nt'表示,对于Linux/Unix用户,它是'posix'。

2、os.getcwd()

函数得到当前工作目录,即当前Python脚本工作的目录路径。

3、os.listdir()

返回指定目录下的所有文件和目录名。

>>> os.listdir(os.getcwd())
['Django', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'MySQL-python-wininst.log', 'NEWS.txt', 'PIL-wininst.log', 'python.exe', 'pythonw.exe', 'README.txt', 'RemoveMySQL-python.exe', 'RemovePIL.exe', 'Removesetuptools.exe', 'Scripts', 'setuptools-wininst.log', 'tcl', 'Tools', 'w9xpopen.exe']
>>> 

4、os.remove()

删除一个文件。

5、os.system()

运行shell命令。

>>> os.system('dir')
0
>>> os.system('cmd') #启动dos

6、os.path.split()

函数返回一个路径的目录名和文件名

>>> os.path.split('C:\\Python25\\abc.txt')
('C:\\Python25', 'abc.txt')

7、os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。

>>> os.path.isdir(os.getcwd())
True
>>> os.path.isfile('a.txt')
False

8、os.path.exists()函数用来检验给出的路径是否真的存在

>>> os.path.exists('C:\\Python25\\abc.txt')
False
>>> os.path.exists('C:\\Python25')
True
>>> 

9、os.path.abspath(name):获得绝对路径

10、os.path.splitext():分离文件名与扩展名

>>> os.path.splitext('a.txt')
('a', '.txt')

11、os.path.join(path,name):连接目录与文件名或目录

>>> os.path.join('c:\\Python','a.txt')
'c:\\Python\\a.txt'
>>> os.path.join('c:\\Python','f1')
'c:\\Python\\f1'
>>> 

12、os.path.basename(path):返回文件名

>>> os.path.basename('a.txt')
'a.txt'
>>> os.path.basename('c:\\Python\\a.txt')
'a.txt'
>>> 

13. 遍历路径下所有文件。

os.walk()

3     import os  
4       
5     def file_name(file_dir):   
6         for root, dirs, files in os.walk(file_dir):  
7             print(root) #当前目录路径  
8             print(dirs) #当前路径下所有子目录  
9             print(files) #当前路径下所有非目录子文件  

os.listdir()

 2     import os  
 3       
 4     def listdir(path, list_name):  #传入存储的list
 5         for file in os.listdir(path):  
 6             file_path = os.path.join(path, file)  
 7             if os.path.isdir(file_path):  
 8                 listdir(file_path, list_name)  
 9             else:  
10                 list_name.append(file_path)  
import os
for filename in os.listdir(r'c:\windows'):
    print filename

 

Part II: glob模块

可以设置文件过滤

import glob
for filename in glob.glob(r'c:\windows\*.exe'):
    print filename

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值