import os os.getcwd() os.chdir('c:\\project') os.chdir(os.getcwd()+'\\exercise') os.mkdir('a') #在當前路徑下建立文件夾 os.makedirs('b') #在當前路徑下建立文件夾 os.makedirs(os.path.abspath('.')+'\\a'+'\\b') #建立含中間路徑下的全部文件夾 os.listdir() #列出當前路徑的全部文件及文件夾
import os path = 'F:\project\exercise' os.path.abspath() #返回標準化路徑 os.path.abspath('.') os.path.abspath(path) path_doc = 'F:\project\exercise\a.docx' os.path.split(path_doc) #將path分割成目錄和文件名的元組 os.path.dirname(path_doc) #返回文件路徑的目錄部分,其結果是os.path.split(path)的第一個元素 os.path.basename(path_doc) #返回文件路徑的文件名部分,其結果是os.path.split(path)的第二個元素
import shutil shutil.move(old_path_doc, new_path_doc)
下面的代碼段能夠爲當前路徑下的全部文件建立一個同名文件夾,並將這些文件移動到其同名文件夾中。python
import os, shutil l = os.listdir() for i in l: j = i.split('.')[0] os.makedirs(j) shutil.move('.\\' + i,'.\\' + j + '\\' + i)
for i in range(5): with open('a0'+str(i+1)+'.docx','w'): pass l = ['a','b','c','d'] for i in l: with open(i + '.docx','w'): pass