Python 常用匯總

來源:互聯網
上載者:User

標籤:help   操作   write   開啟   http   log   div   cpu   format   

Python 熱門檔案操作總結:from random import shuffle判斷檔案夾是否有效:if not os.path.isdir(targetDir):     print ‘Invalid target directory: {}‘.format(targetDir)    sys.exit(2)  判斷檔案夾是否存在:    if not os.path.exists(targetDir):        os.makedirs(targetDir)    列出檔案夾下的所有檔案的名字,不包括路徑:for file in os.listdir(sourceDir):迴圈獲得檔案目錄結構下的各個檔案:http://www.cnblogs.com/herbert/archive/2013/01/07/2848892.htmlfor dir_info in os.walk(image_dir):      root_dir, sub_dirs, file_names = dir_info      for each in dir_info[2]:        xmlName = each.replace(‘.jpg‘, ‘.xml‘) #如果目錄下都是jpg檔案,則將其名字提取,尾碼替換為.xml,然後賦值給XMLName,當然,原來的each 名字不變,if os.path.isfile(in_image = os.path.join(root_dir, file_names)):  #檔案拼接,獲得全路徑,並判斷檔案是否存在    print ‘the file with full path is‘, in_image if not os.path.exists(targetFile): #判斷檔案是否存在    if (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):        open(targetFile, "wb").write(open(sourceFile, "rb").read()) #檔案讀寫:開啟源檔案,寫入目標檔案os.remove(targetFile) #檔案刪除shutil.copy(sourceDir,  targetDir) #複製源檔案到指定目錄,或者可以複製源檔案到指定目錄檔案讀寫file=open(‘labels.txt‘,‘r‘)for eachline in file:    filename1 = eachline.strip().split(‘,‘)  #每一行檔案格式:785,533,905,644,14794983.jpg,Car    filename2 = filename1.replace(‘.jpg‘, ‘.xml‘)     newline = ‘dir_path‘ + ‘/‘ + filename2    txt = open(‘xml.txt‘,‘a‘)    txt.writelines(newline)    txt.write(‘\n‘)    txt.close()file.close()有序字典:from collections import OrderedDicttypenames = OrderedDict()typenames[‘name1‘] = [0, 0]typenames[‘name2‘] = [1, 2]所以有typenames[3] 為[1, 2] typenames[3][0] 為1, typnames[3][1] 值為2對輸入的處理:import argparsedef get_parse_args():    parser = argparse.ArgumentParser(description=‘get the args‘)    parser.add_argument(‘--device‘, dest=‘device_type‘, help=‘device to use‘, default=‘cpu‘, type=str)    if len(sys.argv) == 1:            parser.print_help() #直接可以調用對應的help輸出對應的描述          sys.exit(1)                                         args = parser.parse_args()    return args      # 使用的時候    if __name__ == ‘__main__‘:    args = parse_args()    print(args)    if args.device_type is not None:        dosomething(args.device_type)

 

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.