对文件进行操作,需要使用到的两个库为:import os 、import shutil
1、当前目录的查询:
print('查看当前目录:')
print(os.getcwd())
2、切换目录
print('切换当前目录')
os.chdir('D:\st11\python')
print(os.getcwd())
3、查询指定目录列表
print('显示当前目录下的内容')
print(os.listdir())
print(os.listdir('D:\st11\python\lesson9'))
4、判断是目录还是文件
print('判断是目录还是文件')
print(os.path.isfile('1.txt'))
print(os.path.isdir('lesson1'))
print(os.path.isfile('lesson1'))
(返回值为True或False)
5、新建目录
print('新建目录')
print(os.getcwd())
os.chdir('D:\st11\python\lesson9')
os.mkdir('new4')
os.makedirs('new3\\1\\2')
此处路径最好使用双斜杠
6、删除目录
print('删除目录')
#删除无子目录的目录
print(os.getcwd())
os.chdir('D:\st11\python\lesson9')
os.rmdir('new')
os.rmdir('new1')
os.rmdir('new4')
#删除有子目录的目录
shutil.rmtree('new3')
7、删除文件
print('删除文件')
os.remove('D:\st11\python\lesson9\1.txt')
8、移动文件
shutil.move("旧文件","新文件")
9、复制文件
shutil.copy('1.jpg','4.jpg')
shutil.copy('1.jpg','5.jpg')
10、组合路径
print(os.path.sep)
path='D:\st11\python\lesson9'
f='1.txt'
print(os.path.join(path,f))
print(os.path.sep.join([path,f]))
嗯嗯!!