亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在Python中編輯文本文件中的特定行

在Python中編輯文本文件中的特定行

江戶川亂折騰 2019-07-27 09:55:40
在Python中編輯文本文件中的特定行假設我有一個包含以下內容的文本文件:Dan Warrior 500 1 0有沒有辦法可以編輯該文本文件中的特定行?現在我有這個:#!/usr/bin/env pythonimport io myfile = open('stats.txt', 'r')dan = myfile.readline()print danprint "Your name: " + dan.split('\n')[0]try:     myfile = open('stats.txt', 'a')     myfile.writelines('Mage')[1]except IOError:         myfile.close()finally:         myfile.close()是的,我知道這myfile.writelines('Mage')[1]是不正確的。但是你明白了我的觀點吧?我正在嘗試用Mage替換Warrior來編輯第2行。但我甚至可以這樣做嗎?
查看完整描述

3 回答

?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

你想做這樣的事情:

# with is like your try .. finally block in this casewith open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()print dataprint "Your name: " + data[0]# now change the 2nd line, note that you have to add a newlinedata[1] = 'Mage\n'# and write everything backwith open('stats.txt', 'w') as file:
    file.writelines( data )

原因是你不能直接在文件中執行“更改第2行”之類的操作。您只能覆蓋(而不是刪除)文件的某些部分 - 這意味著新內容僅涵蓋舊內容。所以,如果你在第2行寫“Mage”,那么結果就是'Mageior'。


查看完整回答
反對 回復 2019-07-27
?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

您可以使用fileinput進行就地編輯

import fileinputfor  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line


查看完整回答
反對 回復 2019-07-27
?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

def replace_line(file_name, line_num, text):
    lines = open(file_name, 'r').readlines()
    lines[line_num] = text
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()

然后:

replace_line('stats.txt', 0, 'Mage')


查看完整回答
反對 回復 2019-07-27
  • 3 回答
  • 0 關注
  • 745 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號