Python從txt檔案中逐行讀取資料
阿新 • • 發佈:2018-11-09
Python從txt檔案中逐行讀取資料
# -*-coding:utf-8-*- import os for line in open("./samples/label_val.txt"): print('line=', line, end = '') #後面跟 , end = ''將忽略換行符 #line= ./samples/images/3-3_5460e99f0ca9c410960571e02a0d273c.bmp #line= ./samples/images/5-5_f391afef5c574a0659039595a038ef92.bmp #line= ./samples/images/2-2_518e32236467c850a268ed2ec1d68697.bmp ''' file_obj = open("./samples/label_val.txt") all_lines = file_obj.readlines() #讀取全部內容 for line in all_lines: print('line=', line) file_obj.close() # 寫之前,先檢驗檔案是否存在,存在就刪掉 if os.path.exists("./samples/label_val.txt"): os.remove("./samples/label_val.txt") mylist = ["luoluo", "taotao", "mumu"] # 以寫的方式開啟檔案,如果檔案不存在,就會自動建立 file_write_obj = open("./samples/label_val.txt", 'w') for var in mylist: file_write_obj.writelines(var) file_write_obj.write('\n') file_write_obj.close() '''