本文實例講述了Python文件與文件夾常見基本操作。分享給大家供大家參考,具體如下:
1、判斷文件(夾)是否存在。
1
|
os.path.exists(pathname) |
2、判斷路徑名是否為文件。
1
|
os.path.isfile(pathname) |
3、判斷路徑名是否為目錄。
1
|
os.path.isdir(pathname) |
4、創建文件。
1
2
|
os.mknod(filename) #windows下不可用 open (filename, "w" ) #記得要關閉 |
5、復制文件。
1
2
|
shutil.copyfile( "oldfile" , "newfile" ) #oldfile和newfile都只能是文件 shutil.copy( "oldfile" , "newfile" ) #oldfile只能是文件,newfile可以是文件,也可以是目標目錄 |
6、刪除文件。
1
|
os.remove(filename) |
7、清空文件。
1
2
3
4
|
file = open ( "test.txt" , w) file .seek( 0 ) file .truncate() #注意文件指針的位置 file .close() |
8、創建目錄。
1
2
|
os.mkdir(pathname) #創建單級目錄 os.makedirs(pathname) #遞歸創建多級目錄 |
9、復制目錄。
1
2
|
shutil.copytree( "olddir" , "newdir" ) #olddir和newdir都只能是目錄,且newdir必須不存在 |
10、重命名文件或目錄。
1
|
os.rename(oldname, newname) |
11、移動文件或目錄。
1
|
shutil.move(oldpath, newpath) |
12、刪除目錄。
1
2
3
4
5
6
|
os.rmdir( "dir" ) #不能刪除非空目錄 ''' #可以刪除非空目錄,目錄打開時也能刪除 #約等于'rd /Q /S dir' ''' shutil.rmtree( "dir" ) |
12.1、清空目錄。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#encoding=utf-8 #適用于python3.5+ import os, sys, time, shutil #清空目錄 def ClearDir( dir ): print ( 'ClearDir ' + dir + '...' ) for entry in os.scandir( dir ): if entry.name.startswith( '.' ): continue if entry.is_file(): os.remove(entry.path) #刪除文件 else : shutil.rmtree(entry.path) #刪除目錄 |
13、切換目錄。
1
|
os.chdir(newpath) |
14、open常用模式。
'r': 只讀(缺省。如果文件不存在,則拋出錯誤。)
'w': 只寫(如果文件不存在,則自動創建文件。)
'a': 追加
'r+': 讀寫
15、由全路徑名的到路徑和文件名。
1
2
3
4
5
|
>>> pathfile = r 'D:\abc\def\ghi.txt' >>> os.path.dirname(pathfile) 'D:\\abc\\def' >>> os.path.basename(pathfile) 'ghi.txt' |
16、獲取文件大小。
1
2
|
os.path.getsize(pathfile) #單位為字節(Byte) |
17、獲取當前文件目錄絕對路徑。
1
2
3
4
5
6
|
import os, sys if __name__ = = "__main__" : os.chdir( 'E:\\' ) print (sys.path[ 0 ]) print (os.path.abspath( '.' )) print (os.path.dirname(os.path.abspath(__file__))) |
希望本文所述對大家Python程序設計有所幫助。