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

编程入门 行业动态 更新时间:2024-10-26 06:28:51
本文介绍了在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 04:19:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/678903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   编辑   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!