python對檔案的基本操作

2021-07-04 02:55:48 字數 2143 閱讀 5886

python中對檔案、資料夾的操作需要涉及到os模組和shutil模組。

建立檔案:

1) os.mknod("test.txt") 建立空檔案

2) open("test.txt",'w') 直接開啟乙個檔案,如果檔案不存在則建立檔案

建立目錄:

os.mkdir("file") 建立目錄

建立多層新目錄:

### 建立多層目錄

def mkdirs(path):

# 去除首位空格

path=path.strip()

# 去除尾部 \ 符號

path=path.rstrip("\\")

# 判斷路徑是否存在

# 存在 true

# 不存在 false

i***ists=os.path.exists(path)

# 判斷結果

if not i***ists:

# 建立目錄操作函式

os.makedirs(path)

# 如果不存在則建立目錄

print path + u' 建立成功'

return true

else:

# 如果目錄存在則不建立,並提示目錄已存在

print path + u' 目錄已存在'

return false

複製檔案:

shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是檔案

shutil.copy("oldfile","newfile") oldfile只能是資料夾,newfile可以是檔案,也可以是目標目錄

複製資料夾:

shutil.copytree("olddir","newdir") olddir和newdir都只能是目錄,且newdir必須不存在

重新命名檔案(目錄)

os.rename("oldname","newname") 檔案或目錄都是使用這條命令

移動檔案(目錄)

shutil.move("oldpos","newpos")

刪除檔案

os.remove("file")

刪除目錄

os.rmdir("dir") 只能刪除空目錄

shutil.rmtree("dir") 空目錄、有內容的目錄都可以刪

轉換目錄

os.chdir("path") 換路徑

判斷目標

os.path.exists("goal") 判斷目標是否存在

os.path.isdir("goal") 判斷目標是否目錄

os.path.isfile("goal") 判斷目標是否檔案

備註:若路徑中含中文,在windows環境(編碼為gbk)下,要將目錄編碼成gbk,如:dir.encode('gbk')

python遞迴刪除目錄下的資料夾:

import os

import shutil

def cleandir( dir ):

if os.path.isdir( dir ):

paths = os.listdir( dir )

for path in paths:

filepath = os.path.join( dir, path )

if os.path.isfile( filepath ):

try:

os.remove( filepath )

except os.error:

autorun.exception( "remove %s error." %filepath )#引入logging

elif os.path.isdir( filepath ):

if filepath[-4:].lower() == ".svn".lower():

continue

shutil.rmtree(filepath,true)

return true

dir = "d:\\temp"

cleandir(dir)

python對檔案的幾大基本操作

讀檔案涉及的函式 每乙個檔案都有乙個指標printer,用於記錄讀寫的位置。不管是讀,還是寫,都會從指標的位置開始。乙個字母或數字就是乙個位元組,指標位置 1,回車 n 算兩個位元組,指標位置 2 seek 用於挪動檔案的指標,格式 seek offset,where 有三個模式 where 0時,...

python對檔案操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...

python對檔案操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 返回指定目錄下的所有檔案和目錄名 os.listdir 函式用來刪除乙個檔案 os.remove 刪除多個目錄 os.removedi...