Python-模块:OS,目录及文件的简单操做

1.目录操做spa

#encoding=UTF-8
import unittest,os
from time import sleeprem

print dir(os)
#获取文件路径
'''获取当前路径'''
os.getcwd()
os.path.abspath('')get

#新建目录
os.mkdir('test_file')
#新建多级目录
# os.mkdir('test_file\\test_1\\test_2')it

sleep(4)test

#重命名目录
os.rename('test_file','test-1_file')
f = open('.\\test-1_file\\test.txt', 'w+')
f.close()
import

#删除目录
'''
只能删除空的目录,若目录中有文件或目录抛 WindowsError
'''
os.removedirs('test-1_file')
os.rmdir('test-1_file')coding

 

2.文件操做file

#encoding=UTF-8
import unittest,os
from time import sleepim

print dir(os)命名

#新建文件
'''
以 w或者w+ 打开文件,有此文件则打开,无此文件则新建
'''
f = open('test.txt', 'w+')

#写入文件
f.write('hello world!')
f.close()

#读取文件
f = open('test.txt', 'r')
print f.read()
f.close()
sleep(4)

#重命名文件
os.rename('test.txt','my_test.txt')

#删除文件os.remove('my_test.txt')

相关文章
相关标签/搜索