第二章 python的日常使用

作者: 喜忧参半 | 来源:发表于2022-07-21 00:09 被阅读0次

    1、使用python处理文件与文件夹

    os.getcwd()

    获取当前python程序的运行路径

    import os   
    print(os.getcwd()) 
    >>>D:\PythonProject\bangong
    # windows中采用高反斜杠(\) 作为文件夹之间的分隔符
    # Mac和Linux中采用斜杠(/)作为文件夹之间的分隔符
    # python中反斜杠用于转义符  所以在windows中要打地址 就需要两个反斜杠\\
    

    os.path.join(dir1,dir2,…)

    让python自动处理不同环境下的路径链接

    os.path.join()   
    print(os.path.join('cuda','bin')) 
    --------------------------------------
    Windows下的输出结果:
    'cuda\\bin'
    Mac、Linux下的输出结果:
    'cuda/bin'
    

    os.listdir($path)

    列出path路径下的所有文件和文件夹

    print(os.listdir('E:/Desktop/cuda/'))
    print(os.listdir())   #默认为当前路径
    >>>['.idea', 'learn.py', 'main.py']
    

    os.scandir($path)

    扫描path路径下的文件

    for file in os.scandir():
      print(file.name,file.path,file.is_dir())
    >>>Media C:\Windows\Media True #文件
    >>>mib.bin C:\Windows\mib.bin False #非文件
    
    可以查询被返回的文件
    for file in os.scandir():
     print(file.name, time.ctime(file.stat().st_ctime))  
    # 以kb为当位
     print(file.name,
    datetime.datetime.fromtimestamp(file.stat().st_ctime))
    
    >>>cate.xls Sat Jun 18 01:21:32 2022
    >>>cate.xls 2022-06-18 01:21:32.906468
    
    也可以指定文件mian.py查询信息
    print(os.stat('main.py'))
    print(file.name,file.stat().st_size / pow(2,20))
    #以MB为当位
    

    st_size :文件的体积大小(单位: bytes),除以1024就是KB
    st_atime:文件的最近访问时间
    st_mtime:文件的最近修改时间
    st_ctime: Windows下表示创建时间
    st_birthtime:只在Mac、Linux下可用,表示创建时间

    由于atime mtime ctime 都是从1970到现在的秒数 因此可以载入time模块 转化时间
    转化法一: import time time.ctime(filetime)
    转化法二: import datetime datetime.datetime.fromtimestamp(filetime)
    在datetime转化后,可以通过datatime.datatime.fromtimestamp().hour/minute/second/year

    例如找出path路径下某个后缀结尾的文件(不递归查询)
    import os
    def findend(str):
        path = 'C:\\Windows\\System32'
        count = 0
        files = []
        for file in os.scandir(path):
            if os.path.isdir(file) == False:
                files.append(file)
        for file in files:
            if file.name.endswith(f'.{str}'):
                count = count + 1
                print(file,count)
    findend('png')
    >>> <DirEntry 'wpcmon.png'> 1
    
    找出某个路径及以下某个后缀结尾的文件(递归查询)

    方法一:

    def findend(str):
        path = 'C:\\Windows\\System32'
        count = 0
        files = []
        for dirname,dirpath,filesname in os.walk(path):
    #如果只查找filesname则返回值为元组
            for filename in filesname:
                if filename.endswith(f'.{str}'):
                    files.append(filename)
                    count = count + 1
                    print(dirname,filename,count)
    findend('png')
    >>> C:\Windows\System32 wpcmon.png 61
    

    方法二:

    def findend(str):
     path = 'C:\\Windows\\System32'
     print(glob.glob(f'{path}/*.{str}', recursive=True))
    findend('dll')
    

    f.readlines()

    打开文件,读取内容

    f = open('file1.txt','r','encoding='utf-8') #打开文件
      text = f.readlines()  #读取文件
        print(text)  #输出文件
    f.close  #关闭文件
    

    f.write()

    写入文件内容

    with open('file2.txt','w',encoding='utf-8')as f:
      text = '第一行内容\n 第二行内容'
      f.write(text)
    

    TemporaryFile()

    创建临时读取文件,程序运行完后自动删除

    from tempfile import TemporaryFile
    f = TemporaryFile('w+')  #w+ 表示读取及写入文件
    f.write('Hello phato!')
    f.seek(0)  #写完后光标需要回到文件开头位置
    data = f.readlines()
    print(data)
    f.close()
    

    TemporaryDirectory()

    创建临时文件夹

    from tempfile import TemporaryDirectory
    with TemporaryDirectory() as temp_folder:
      print(f'临时文件夹已经创建:{temp_folder}')
    >>>临时文件夹已经创建:C:\Users\AppData\Temp\tmpkx
    

    os.walk(path)

    遍历子文件目录

    import os
    for dirpath,dirname,filenames in os.walk(path):
      print(f'发现文件夹:{dirpath}')
      print(filenames)
    >>>发现文件夹:./new1\new4
    >>>['f.txt', 'firstname.txt']
    

    字符串.startwith() 字符串.endswith()
    .startwith() 和.endswith() 以什么开头,以什么结尾
    print('abc.txt'.startswith('ab'))
    print('abc.txt'.endswith('.txt'))
    # 字符串A.startswith(字符串B):字符串A是否以字符串B开头
    # 字符串A.endswith(字符串B)  :字符串A是否以字符串B结尾
    

    glob.glob(str,recursive)

    寻找通配符形式 通配符有* ? [seq] -[0-9] [A-Z] ![seq] ![0-9]

    import glob
    print(glob.glob('*py'))  
    #找出当前文件夹下的py文件
    print(glob.glob('**/*.txt',recursive=True)) 
    #向下递归找出子文件夹的txt文件
    

    fnmatch.fnmatch(str)

    用来匹配文件名

    import fnmatch
    print(fnmatch.fnmatch('mmakerbean','m*an'))
    >>>True
    print(fnmatch.fnmatch('filename.txt','fil*.txt'))
    >>>True
    

    os.exists() 与 os.mkdir()、os.makedirs()

    创建文件夹

    import os 
    if not os.path.exists('new_filename')
      os.mkdir('new_filename')
    #迭代创建多级目录
    os.makedirs('第一级dir/第二级dir/第三级dir')
    

    shutil.copy() 或 shutil.move()

    用来进行文件处理,可以复制、移动、删除
    shutil.copy(filename,path或path/rename)
    shutil.copytree(dirname,path或path/rename)

    import shutil
    shutil.copy('E:/top/first.txt','./new1/new2/')
    #复制文件first.txt到指定目录/new2/下
    shutil.copytree('new2/','new1/new/')
    #将new2文件夹下的文件复制到new1下的new文件夹中
    

    shutil.move(filename,path)
    shutil.rmtree(dirname)

    import shutil
    shutil.move('new1/new2/first.txt','new2/f2.txt') 
    #frist.txt文件移动并从重命名为f2.txt
    shutil.move('new1/f.txt','new2/')  
    #f.txt文件移动到new2目录下
    shutil.move('new2','new1/new4')  
    #new2目录移动到new1目录的new4文件夹下
    shutil.rmtree('new1/new2')   
    #迭代删除文件夹及其子文件夹
    

    os.rename() os.remove

    文件的重命名与删除

    import os
    os.rename('f2.txt','new1/f2.txt')
    #重命名文件,具有移动功能
    os.remove('new1/f2.txt')
    #删除文件
    

    删除某个目录下所有指定后缀的文件
    import shutil
    def remdir(path,endstr):
        for dirname,dirpath,filesname in os.walk(path):
            for filename in filesname:
                if filename.endswith(endstr):
                   print('Deleting  ' + dirname+'\{}'.format(filename))
                   os.remove(dirname+'\{}'.format(filename))
        print('Delete successfully!!')
    
    remdir('F:\迅雷下载','zip')
    >>> Deleting  F:\迅雷下载\yjmdl.zip
    >>> Delete successfully!!
    
    删除某个目录下指定后缀的文件及其父文件夹
    #这个操作一定要谨慎,因为只要含有某个后缀的文件夹都会被删除
    import os,shutil
    def remdir(path,endstr):
        for dirname,dirpath,filesname in os.walk(path):
            for filename in filesname:
                if filename.endswith(endstr):
                    print('Deleting  ' + dirname+'\{}'.format(filename))
                    shutil.rmtree(dirname)
        print('Delete successfully!!')
    

    更改某个目录下所有文件的文件名

    这个方法主要解决很多很长的前缀名文件,为了缩短前缀名而修改文件名。

    import os
    def rnfile(filepath,pun,punum):
        for dirpath,dirname,filesname in os.walk(filepath):
            for filename in filesname:
                if filename.startswith(pun):
                    newname = filename[int(punum):]
                    # print(dirpath+f'/{filename}')
                    print('rename: '+ dirpath + '/{}'.format(filename), +'—→'+dirpath + '/{}'.format(newname))
                    os.rename(dirpath + '/{}'.format(filename),dirpath + '/{}'.format(newname))
    rnfile('K:\数据分析方法','【','16')
    

    zipfile.ZipFile(zip_path,'r')

    读取压缩包内的文件

    with zipfile.ZipFile('./project.zip','r') as zipobj:
        for file_name in zipobj.namelist():
            print(file_name.encode('cp437').decode('gbk'))
    #处理压缩包中的cp437编码为中文转码gbk
    
    zipobj.getinfo(file_name)

    读取压缩包内文件信息

    with zipfile.ZipFile('./project.zip','r') as zipobj:
        for file_name in zipobj.namelist():
            info = zipobj.getinfo(file_name)
            new_file_name = file_name.encode('cp437').decode('gbk')# 调整编码
            print(new_file_name,info.file_size,info.compress_size)
    #info.file_size :原始文件大小   info.compress_size:压缩后文件大小  输出是字节
    
    zipobj.extract(zip_file_name,zip to path)

    解压压缩包中的文件

    with zipfile.ZipFile('./project.zip','r') as zipobj:
        zipobj.extract('feee.txt','./') #将其中的feee文件解压到当前目录下
        zipobj.extractall('./') #q全部解压到当前目录下,
       # zipobj.extractall(path,pwd=b'key')   密码输入时需有个b
    
    zipobj.write(filename/filelist)

    创建压缩包

    file_list = ['main.py','learn.py']  #将py文件打包压缩
    with zipfile.ZipFile('pyzip.zip','w') as zipobj:
        for file in file_list:
            zipobj.write(file)
    #追加压缩   就是 with zipfile.ZipFile('pyzip.zip','a') as zipobj:  
    #用a 追加
    

    相关文章

      网友评论

        本文标题:第二章 python的日常使用

        本文链接:https://www.haomeiwen.com/subject/adhyirtx.html