zoukankan      html  css  js  c++  java
  • Python之文件操作:经验总结

    1、怎么判断读出来的文件是gbk还是utf-8编码
    if content == u'中国'.encode('gbk'):
        return 'gbk'
    elif content == u'中国'.encode('utf-8'):
        return 'utf-8'
     
    2、
    if not os.path.exists(filePath):
        os.mkdir(filePath)
    判断目录是否存在,不存在的情况才会去创建
    if os.path.exists(dirPath):
        for root,dirs,files in os.walk(dirPath):
    遍历一个目录之前先判断路径是否存在
     
    3、使用系统命令copy文件
    os.system('copy e:\tmp\t23.txt e:\tmp\t999.txt')
     
    4、文件操作,对于路径等所有可能情况的处理
    输入源文件所在路径和目标目录路径,然后实现文件拷贝功能
    # encoding=utf-8
    import os
    对于源目录和目标目录所有可能的情况做了异常情况的处理
    def copy(resF, desF):
        resF = os.path.normpath(resF)
        desF = os.path.normpath(desF)
        if not os.path.exists(resF):
            print 'file not exists'
            return False
        elif resF == desF:
            print 'desF error'
            return False
        elif os.path.exists(desF):
        while True:
            print u'覆盖%s吗?(y/n)'%desF,
            inputVar = raw_input().lower()
            if inputVar == 'n':
                print u'文件已存在,复制0个文件'
                    return False
           elif inputVar == 'y':
               os.remove(desF)
               break
          else:
                continue
        with open(resF) as fp:
            content = fp.read()
        with open(desF,'w') as fp:
            fp.write(content)
        print u'已复制1个文件'
        return True
     
    if __name__ == '__main__':
        copy('e:\tmp\t23.txt', 'e:\tmp\t1234.txt')
     
    5、当某种文件的格式比较多但是可以枚举出来的时候,可以全部枚举出来放入列表中
    遍历某个目录下的所有图片,并在图片名称后面增加_xx
    picEnds = ['.jpg','.jpeg','.bpm','.png','.gif']
  • 相关阅读:
    Transact_SQL小手册
    使用泛型的 TArray 从动态数组中查找指定元素
    使用泛型的 TArray 为动态数组排序
    使用 InputBox、InputQuery 的启发
    近况汇报
    泛型排序器 TComparer
    详测 Generics Collections TList (2): First、Last、IndexOf、LastIndexOf
    详测 Generics Collections TList (1): Add、Clear、Count、Capacity
    WindowsAPI: MulDiv
    SendTextMessage 等方便的消息发送函数
  • 原文地址:https://www.cnblogs.com/emily-qin/p/7001277.html
Copyright © 2011-2022 走看看