本文共 1837 字,大约阅读时间需要 6 分钟。
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 | 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" ) |
13、切换目录。
1 | os.chdir(newpath) |
14、open常用模式。
1 2 3 4 | '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 3 | os.path.getsize(pathfile) #单位为字节(Byte) #or os.stat(pathfile).st_size |
17、获取文件创建/修改/访问时间。
1 2 3 | os.path.getctime(pathfile) #创建时间 os.path.getmtime(pathfile) #修改时间 os.path.getatime(pathfile) #访问时间 |
18、获取当前文件目录绝对路径。
1 2 3 4 5 6 7 | 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__))) |
19、文件同步。
1 2 3 | fileObj.write(text) fileObj.flush() os.fsync(fileObj.fileno()) |
20、获取文件扩展名
1 2 3 4 | >>> os.path.splitext(r 'D:\tmp\3.jpg' )[ 1 ] '.jpg' >>> os.path.splitext( '3.jpg' )[ 1 ] '.jpg' |
相关阅读:
1、
2、
3、
*** ***
本文转自walker snapshot博客51CTO博客,原文链接http://blog.51cto.com/walkerqt/1264285如需转载请自行联系原作者
RQSLT