在 Python 中编辑文本文件中的特定行 [英] Editing specific line in text file in Python

查看:32
本文介绍了在 Python 中编辑文本文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a text file containing:

Dan
Warrior
500
1
0

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

Is there a way I can edit a specific line in that text file? Right now I have this:

#!/usr/bin/env python
import io

myfile = open('stats.txt', 'r')
dan = myfile.readline()
print dan
print "Your name: " + dan.split('
')[0]

try:
    myfile = open('stats.txt', 'a')
    myfile.writelines('Mage')[1]
except IOError:
        myfile.close()
finally:
        myfile.close()

是的,我知道 myfile.writelines('Mage')[1] 不正确.但你明白我的意思,对吗?我正在尝试通过将 Warrior 替换为 Mage 来编辑第 2 行.但我什至可以这样做吗?

Yes, I know that myfile.writelines('Mage')[1] is incorrect. But you get my point, right? I'm trying to edit line 2 by replacing Warrior with Mage. But can I even do that?

推荐答案

你想做这样的事情:

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

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

这样做的原因是您不能直接在文件中执行更改第 2 行"之类的操作.您只能覆盖(而不是删除)文件的一部分 - 这意味着新内容只会覆盖旧内容.因此,如果您在第 2 行上写了Mage",则结果行将是Mageior".

The reason for this is that you can't do something like "change line 2" directly in a file. You can only overwrite (not delete) parts of a file - that means that the new content just covers the old content. So, if you wrote 'Mage' over line 2, the resulting line would be 'Mageior'.

这篇关于在 Python 中编辑文本文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆