通过小程序练习Python中关于os模块的方法
来源:互联网 发布:航天五院西安分院知乎 编辑:程序博客网 时间:2024/05/11 22:35
通过一个小程序来熟悉一下os模块中的方法,OS模块在以后会经常的使用,操作目录与文件等
import osprint os.getcwd()for tmpdir in ('/tmp',r'c:\temp',r'd:\temp'): if os.path.isdir(tmpdir): ##判断上面元组中的元素是否存在并且为一个目录 breakelse: print 'No temp dir available' tmpdir = '' os.chdir('d:') ##我这里直接转到d分区了 os.makedirs('temp1') ##建立temp1文件夹 print os.getcwd() ## 获得当前目录路径if tmpdir: os.chdir(tmpdir) ##切换文件夹 cwd = os.getcwd() print 'Current temp dir is %s ' % cwd print 'Now it will create an dir...' dirname = os.listdir(cwd) ##显示当前目录下的文件,放到一个列表中 print dirname os.makedirs('example1') ##建立一个新的文件夹,example os.chdir('example1') cwd = os.getcwd() print 'Now the current dir is %s ' % cwd print 'The original dir listing is:' print os.listdir(cwd) print 'Now it will create a test file' fobj = file('test.txt','w') fobj.write('foo\n') fobj.write('bar\n') fobj.close() print 'Now after create a test file the listing is :' print os.listdir(cwd) ##这里会创建一个文件,里面有foo bar 这两行字符 print 'Now it will change the test.tex to test.ini' os.rename('test.txt','test.ini') ##rename print os.listdir(cwd) path = os.path.join(cwd,os.listdir(cwd)[0]) ##path 此时为 d:\temp\example1\test.ini print 'The full file pathname is %s' % path print os.path.split(path) ## ['d:\\temp\\example1', 'test.ini'] split() 函数返回 dirname(目录名) 与 basename(文件名+扩展名)的一个元组 print os.path.splitext(os.path.basename(path)) ##('test', '.ini') splittext() 函数返回filename(文件名)与extension(扩展名)的一个元组
- 通过小程序练习Python中关于os模块的方法
- Python中 os、shutil 模块实用方法
- os、os.path 模块中关于文件、目录常用的函数使用方法(python)
- os、os.path模块中关于文件、目录常用的函数方法
- Python中os模块
- Python中OS模块
- python 中os模块
- Python中os模块
- Python中os模块的使用
- python中OS模块的常用命令
- Python 中 os 模块的使用
- python中os.path模块的使用
- python练习小程序
- python小程序练习
- python的OS模块
- Python的os模块
- python的os模块
- python的os模块
- 一个简单的游戏服务器框架
- 例题6.1.1
- C语言指针和数组详解
- 汇编——单重循环
- 详细介绍C/C++数组名与指针区别
- 通过小程序练习Python中关于os模块的方法
- 【转】void 及 void*
- C指针的实质
- android.intent.action大全
- LeetCode Covert Sorted List to Binary Search Tree
- 防止表单重复提交
- Android中的AppWidget
- Matlab化简符号表达式
- MySQL JDBC URL中的格式以及参数介绍