Re: [問題] 檔案空白刪除

看板Python作者時間13年前 (2012/05/05 09:17), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/4 (看更多)
同時讀寫用'r+' with open("a.txt","r+") as f: pos_read, pos_writen = 0, 0 line = None while '' != line: line = f.readline() if '' == line.strip():continue pos_read = f.tell() # overwrite f.seek(pos_writen,0) f.write(line) pos_writen = f.tell() # put pointer back for reading f.seek(pos_read) # drop everything else f.truncate(pos_writen) 不過小弟這邊處理的文字檔通常大不到哪裡 所以會用這種相較起來好懂的寫法 content = [] with open("a.txt","r") as fin: content = [line for line in fin if ''!=line.strip()] with open("a.txt","w") as fout: fout.writelines(content) ※ 引述《shihyuyao (shihyuyao)》之銘言: : ※ 引述《Jason1122 (Jason1122)》之銘言: : : w再開一個檔案來存: : : with open("t.txt", "r") as f: : : with open("t2.txt", "w") as o: : : for line in f: : : if line != "\n": : : o.write(line) : : t2改成t會變空白,同個檔案可能要別的方法吧 : : 1.txt : : AAA : : BBB : : CCC : : 2.txt 拿掉空白變成 : : AAA : : BBB : : CCC : : 我想把1.txt 每列的空白刪除,有辦法在同一個檔案做完嗎? : : 還是要再開另一個檔案2.txt才可以? : : 讀出的每一列怎麼判斷是不是空白? : : infile = open(1.txt, 'r'); : : outfile = open(2.txt, 'w'); : : for line in infile: : : //這邊要怎麼判斷空白跳過在檔案輸出到2.txt? : : 謝謝 : +++++++++++++++++++++++++++++++++++++++++++ : if line != "\n": : 這樣是比對字串最後一個字元嗎? : AAA後面還有一個"\n"?? 幫回 這是比整行 AAA\n != \n 寫入 \n == \n 不理 \n == \n 不理 BBB\n != \n 寫入 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 111.255.10.61
文章代碼(AID): #1Ff7-voF (Python)
討論串 (同標題文章)
文章代碼(AID): #1Ff7-voF (Python)