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

查看:260
本文介绍了在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('\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行。但我能做到吗?

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\n'

# 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天全站免登陆