在Python中编辑文本文件中的特定行

2024-05-21 12:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个文本文件包含:

Dan
Warrior
500
1
0

有没有方法可以编辑该文本文件中的特定行?现在我有这个:

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "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]不正确。但你明白我的意思,对吧?我试图用法师代替战士来编辑第2行。但我能做到吗?


Tags: 方法txt编辑writelinescloseusrstatsopen
2条回答

你想这样做:

# with is like your try .. finally block in this case
with open('stats.txt', 'r') as file:
    # read a list of lines into data
    data = file.readlines()

print data
print "Your name: " + data[0]

# now change the 2nd line, note that you have to add a newline
data[1] = 'Mage\n'

# and write everything back
with open('stats.txt', 'w') as file:
    file.writelines( data )

原因是不能直接在文件中执行“更改第2行”之类的操作。您只能覆盖(而不是删除)文件的部分,这意味着新内容只覆盖旧内容。所以,如果你在第2行上写“Mage”,那么得到的行就是“Mageior”。

您可以使用fileinput进行就地编辑

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line
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')

相关问题 更多 >