1、判断文件(夹)是否存在。

os.path.exists(pathname)

2、判断路径名是否为文件。

os.path.isfile(pathname)

3、判断路径名是否为目录。

os.path.isdir(pathname)

4、创建文件。

os.mknod(filename)    #windows下不可用
open(filename, "w")   #记得要关闭

5、复制文件。

shutil.copyfile("oldfile", "newfile")   #oldfile和newfile都只能是文件,目标文件会被覆盖
shutil.copy("oldfile", "newfile")   #oldfile只能是文件,newfile可以是文件,也可以是目标目录

6、删除文件。

os.remove(filename)

7、清空文件。

file = open("test.txt", w)
file.seek(0)     
file.truncate() #注意文件指针的位置
file.close()

8、创建目录。

os.mkdir(pathname)        #创建单级目录
os.makedirs(pathname)     #递归创建多级目录

9、复制目录。

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

10、重命名文件或目录。

os.rename(oldname, newname)

11、移动文件或目录。

shutil.move(oldpath, newpath)

12、删除目录。

os.rmdir("dir")     #不能删除非空目录
'''
#可以删除非空目录,目录打开时也能删除
#约等于'rd /Q /S dir'
'''
shutil.rmtree("dir")

13、切换目录。

os.chdir(newpath)

14、open常用模式。

'r':  只读(缺省。如果文件不存在,则抛出错误。)
'w':  只写(如果文件不存在,则自动创建文件。)
'a':  追加
'r+': 读写

15、由全路径名的到路径和文件名。

>>> pathfile = r'D:\abc\def\ghi.txt'
>>> os.path.dirname(pathfile)
'D:\\abc\\def'
>>> os.path.basename(pathfile)
'ghi.txt'

16、获取文件大小。

os.path.getsize(pathfile)    #单位为字节(Byte)
#or
os.stat(pathfile).st_size

17、获取文件创建/修改/访问时间。

os.path.getctime(pathfile)    #创建时间
os.path.getmtime(pathfile)    #修改时间
os.path.getatime(pathfile)    #访问时间

18、获取当前文件目录绝对路径。

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、文件同步。

fileObj.write(text)
fileObj.flush()
os.fsync(fileObj.fileno())

20、获取文件扩展名

>>> os.path.splitext(r'D:\tmp\3.jpg')[1]
'.jpg'
>>> os.path.splitext('3.jpg')[1]
'.jpg'


相关阅读:

1、自定义文件夹处理函数(Python)

2、Python遍历目录更换文件名和目录名

3、关于python文件操作


*** walker的流水账 ***