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

标签 python io

假设我有一个包含以下内容的文本文件:

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] 不正确。但你明白我的意思,对吧?我正在尝试通过用 Mage 替换 Warrior 来编辑第 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”。

关于python - 在 Python 中编辑文本文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4719438/

相关文章:

python - 在 Jupyter Notebook 演示文稿中隐藏代码

python - 从游标创建临时表

python - 努力让 Sum() 函数从列表中输出一个值

linux - IO 阻塞进程是否会在 'top' 输出中显示 100% 的 CPU 使用率?

java - 在 Java 中 File.canExecute() 究竟做了什么?

python - 如何使用python去除图像中的椒盐噪声?

python - 'dict' 对象没有属性 'HTTP_REFERER'

c - 如何在c中逐行读取?

python - 我如何拆分这个字符串?

c - 引用 fgets,\0 如何合并到普通文本文件中