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

原文由 test 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 322
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”。

原文由 Jochen Ritzel 发布,翻译遵循 CC BY-SA 2.5 许可协议

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')

原文由 Peter C 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题