1、判断目录是否存在、判断文件是否存在、创建目录、重命名目录或文件
import os #获取当前目录路径: E:WorkProjectspython print(os.getcwd()) #判断当前目录是否存在,不存在则创建目录dir1 if not os.path.isdir('dir1'): os.mkdir('dir1') #判断指定目录是否存在,不存在则创建目录dir22 if not os.path.isdir('E:WorkProjectspythondir22'): os.mkdir('E:WorkProjectspythondir22') #判断当前目录的指定文件是否存在 print(os.path.isfile('file1.txt')) #重命名目录dir22为dir2(rename也可用于文件) os.rename('dir22', 'dir2') #切换到目录dir2 os.chdir('dir2') #切换到目录dir2后获取当前目录路径: E:WorkProjectspythondir2 print(os.getcwd())
2、目录和文件的查询
当前目录结构为
│ 1.txt
│ 2.txt
│ test1.py
│
├─dir1
│ dir1_1.txt
│ dir1_2.txt
│
└─dir2
(1)获取指定目录下的目录和文件列表(不包括子目录)
import os path = os.getcwd() for filename in os.listdir(path): print(os.path.join(path,filename)) '''运行结果: E:WorkProjectspython1.txt E:WorkProjectspython2.txt E:WorkProjectspythondir1 E:WorkProjectspythondir2 E:WorkProjectspython est1.py '''
(2)递归获取指定目录下的目录和文件列表(包括子目录)
import os path = os.getcwd() #walk产生3元组:目录路径,目录名称,文件名 for dirpath,dirnames,filenames in os.walk(path): print("dirpath:{};dirnames:{};filenames:{}".format(dirpath,dirnames,filenames)) '''运行结果: dirpath:E:WorkProjectspython;dirnames:['dir1', 'dir2'];filenames:['1.txt', '2.txt', 'test1.py'] dirpath:E:WorkProjectspythondir1;dirnames:[];filenames:['dir1_1.txt', 'dir1_2.txt'] dirpath:E:WorkProjectspythondir2;dirnames:[];filenames:[] ''' for dirpath,dirnames,filenames in os.walk(path): #输出所有文件 for filename in filenames: print(os.path.join(dirpath, filename)) #输出所有目录 for dirname in dirnames: print(os.path.join(dirpath, dirname)) '''运行结果: E:WorkProjectspython1.txt E:WorkProjectspython2.txt E:WorkProjectspython est1.py E:WorkProjectspythondir1 E:WorkProjectspythondir2 E:WorkProjectspythondir1dir1_1.txt E:WorkProjectspythondir1dir1_2.txt '''
3、获取文件信息
import os import time filepath = r'E:WorkProjectspython1.txt' #分割路径,返回一个元组(目录,文件名),结果:('E:\Work\Projects\python', '1.txt') print(os.path.split(filepath)) #返回目录部分,结果:E:WorkProjectspython print(os.path.dirname(filepath)) #返回文件名,结果:1.txt print(os.path.basename(filepath)) #返回文件大小(单位为字节),结果:1296 print(os.path.getsize(filepath)) #返回目录或文件的创建时间、最后修改时间、最后访问时间(单位为新纪元1970年1月1日到访问时的秒数) ctime = os.path.getctime(filepath) mtime = os.path.getmtime(filepath) atime = os.path.getatime(filepath) #结果例子:1566436201.5443518 1566439077.5319004 1566439099.905073 print(ctime, mtime, atime) #Unix时间戳转换成时间 def unix2time(unix): time_local = time.localtime(unix) dt = time.strftime("%Y-%m-%d %H:%M:%S",time_local) return dt #将Unix时间戳转换成时间 #结果例子:2019-08-22 09:10:01 2019-08-22 09:57:57 2019-08-22 09:58:19 print(unix2time(ctime),unix2time(mtime),unix2time(atime))
4、目录和文件的移动、拷贝、删除
当前目录结构为
│ 1.txt
│ 2.txt
│ test1.py
│
├─dir1
│ dir1_1.txt
│ dir1_2.txt
│
└─dir2
import shutil #拷贝整个目录 shutil.copytree('dir1','dir1_bak') #拷贝单个文件,第2个参数可以是目录,也可以是文件名 shutil.copy('1.txt', 'dir2/1_bak.txt') shutil.copy('2.txt', 'dir2') #移动目录或文件 shutil.move('dir1', 'dir2') shutil.move('1.txt', 'dir2') #删除整个目录 shutil.rmtree('dir1_bak')