import os
os.mkdir('新資料夾')
注意如果要建立的資料夾已經存在的話會報錯的
import os
if not os.path.exists('新資料夾'):
os.mkdir('新資料夾')
import os
os.makedirs('第一層資料夾/第二層資料夾/第三層資料夾')
shutil.copy(要複製的檔案,要複製的位置)shutil.copytree(要複製的資料夾,要複製到的新資料夾位置)import shutil
shutil.copy('file1.txt', './新資料夾')
shutil.copy('file1.txt', './新資料夾/new_file.txt') #把檔案再重新命名
import shutil
shutil.copytree('新資料夾', '新新的資料夾')
shutil.move(要移動的檔案/資料夾, 要移動的位置)import shutil
shutil.move('file1.txt','新資料夾/file3.txt')
shutil.move('file1.txt','新資料夾/')
shutil.move('新資料夾','新新資料夾/')
os.rename(要重新命名的檔案/資料夾, 新的名字)import os
os.rename('新資料夾', 'hxx資料夾')
os.rename('file1.txt', 'new.txt')
os.remove(要刪除的檔案)注意只能刪檔案,如果是資料夾則會出錯shutil.rmtree(要刪除的資料夾)import os
os.remove('file1.txt')
import shutil
shutil.rmtree('新新資料夾')
os.listdir(指定的絕對路徑或相對路徑)
import os
#這3種寫法都可以
os.path.isfile(檔名) #如果目錄不存在就返回false
os.path.exists(檔名) #如果檔案不存在就返回false
os.path.exists(資料夾名) #如果目錄不存在就返回false
os.walk()import os
os.path.isfile('test.txt') #如果不存在就返回false
os.path.exists('新資料夾') #如果目錄不存在就返回false
返回乙個3個元素的元組,(dirpath,dirnames,filenames).
import os
for dirpath,dirname,filename in os.walk('data/'):
for dir in dirname:
print(dir)
for file in filename:
print(file)
Python 檔案及資料夾操作
1.建立檔案 1.1 使用常規方式 建立開啟並關閉檔案 fp open file name.txt fp.close 1.2 建立檔案 推薦使用上下文管理器 with open 123 file name.txt a as fp pass 1.3 linux可以使用os.mknod 因為在windo...
python檔案及資料夾操作
一 python中對檔案 資料夾操作時經常用到的os模組和shutil模組常用方法。1.得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 2.返回指定目錄下的所有檔案和目錄名 os.listdir 3.函式用來刪除乙個檔案 os.remove 4.刪除多個目錄 os.re...
python 檔案及資料夾操作
需要importos 表示當前目錄 當前目錄的父目錄 s os.getcwd 得到當前工作目錄,即當前python指令碼工作的目錄路徑 d ss py os.chdir r d ss 改變工作目錄 os.curdir 表示當前目錄 s os.pardir 表示當前目錄的父目錄 os.chdir os...