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

发布于 2021-02-02 23:13:38

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

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

是的,我知道那·是不正确的。但是你明白我的意思吧?我正在尝试通过用Mage替换Warrior来编辑第2行。但是我还能做到吗?

关注者
0
被浏览
107
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你想做这样的事情:

    # 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”。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看