假设我有一个包含以下内容的文本文件:
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/