Python之檔案操作:經驗總結

來源:互聯網
上載者:User

標籤:情況   pat   open   res   import   sys   root   name   判斷   

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-8import 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、當某種檔案的格式比較多但是可以枚舉出來的時候,可以全部枚舉出來放入列表中遍曆某個目錄下的所有圖片,並在圖片名稱後面增加_xxpicEnds = [‘.jpg‘,‘.jpeg‘,‘.bpm‘,‘.png‘,‘.gif‘]

Python之檔案操作:經驗總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.