Re: [問題] 檔案移動行數
※ 引述《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
Python 近期熱門文章
PTT數位生活區 即時熱門文章