在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行。但是我还能做到吗?

Jochen Ritzel:

您想做这样的事情:

# 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”。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章