Re: [問題] 檔案移動行數

看板Python作者 (←這人是超級笨蛋)時間12年前 (2013/09/19 21:22), 編輯推噓1(101)
留言2則, 1人參與, 最新討論串1/1
※ 引述《yshihyu (yshihyu)》之銘言: : 用 open 開啟一個檔案 : 想移到某些行數之後插入一個字串, 請問有辦法辦到嗎? : 謝謝 假設我有一個檔案 lipsum.txt Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis urna quis sapien accumsan, nec fermentum felis tempor. Etiam ante felis, lacinia a faucibus eu, dictum eu mi. 然後我想在第三行的 ante 後面插入一個字 "ultrices" with open('lipsum.txt', 'r+') as f: # 前往要插入的位置 for i in range(2): f.readline() f.seek(11, 1) # 跳過第三行一開始的 'Etiam ante ' pos = f.tell() # 記住目前的位置 rest_of_file = f.read() # 把剩下的讀進來 f.seek(pos) # 回到要插入的位置 f.truncate() # 先把後面的刪掉 f.write('ultrices ') f.write(rest_of_file) 如果有不懂的函式與參數請自行參閱官方文件 http://docs.python.org/2/tutorial/inputoutput.html 注意其實沒辦法真的辦到在檔案中間「插入」字串這種事 我們只能先把後面的讀進來, 之後再寫回去 -- ╱ ̄ ̄ ̄╲ ▏◢█◣ 成龍表示: 是喔... ′/ ‵ ╰╯ ψQSWEET █◤ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.81.146

09/27 00:18, , 1F
其實我也在想有沒有別的方法。
09/27 00:18, 1F

09/27 00:18, , 2F
看大大回了,才知道方法真的不多。
09/27 00:18, 2F
文章代碼(AID): #1IElgR6x (Python)
文章代碼(AID): #1IElgR6x (Python)