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

1.目录操作

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

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

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

sleep(4)

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

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

2.文件操作

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

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')

原文地址:https://www.cnblogs.com/yan-xiang/p/6866607.html