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

tes*_*est 68 python io

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

Dan
Warrior
500
1
0
Run Code Online (Sandbox Code Playgroud)

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

#!/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()
Run Code Online (Sandbox Code Playgroud)

是的,我知道这myfile.writelines('Mage')[1]是不正确的.但是你明白了我的观点吧?我正在尝试用Mage替换Warrior来编辑第2行.但我甚至可以这样做吗?

Joc*_*zel 91

你想做这样的事情:

# 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 )
Run Code Online (Sandbox Code Playgroud)

原因是你不能直接在文件中执行"更改第2行"之类的操作.您只能覆盖(而不是删除)文件的某些部分 - 这意味着新内容仅涵盖旧内容.所以,如果你在第2行写"Mage",那么结果就是'Mageior'.

  • 不好..如果您有20 Gb文件怎么办? (7认同)
  • 假设是正确的,这是小文件首选的解决方案吗?否则,我们可能需要大量内存来存储数据.而且,即使是1次编辑,我们也需要再次编写整个内容. (5认同)
  • 嗨Jochen,语句"打开(文件名,模式)"也会在程序退出后隐式关闭文件名,对吧? (2认同)

gho*_*g74 19

您可以使用fileinput进行就地编辑

import fileinput
for  line in fileinput.FileInput("myfile", inplace=1):
    if line .....:
         print line
Run Code Online (Sandbox Code Playgroud)


Pet*_*r C 17

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()
Run Code Online (Sandbox Code Playgroud)

然后:

replace_line('stats.txt', 0, 'Mage')
Run Code Online (Sandbox Code Playgroud)

  • 这会将整个文件的内容加载到内存中,如果文件很大,这可能不是一件好事. (8认同)
  • @SteveNg 你有解决你注意到的问题的方法吗?这个答案和接受的答案都依赖于将整个文件加载到内存中 (2认同)

Ase*_*dav 7

您可以通过两种方式来做到这一点,选择适合您需求的方式:

方法I。)使用行号替换。enumerate()在这种情况下,您可以使用内置函数:

首先,在读取模式下,将所有数据保存在一个变量中

with open("your_file.txt",'r') as f:
    get_all=f.readlines()
Run Code Online (Sandbox Code Playgroud)

其次,写入文件(在其中枚举生效)

with open("your_file.txt",'w') as f:
    for i,line in enumerate(get_all,1):         ## STARTS THE NUMBERING FROM 1 (by default it begins with 0)    
        if i == 2:                              ## OVERWRITES line:2
            f.writelines("Mage\n")
        else:
            f.writelines(line)
Run Code Online (Sandbox Code Playgroud)

方法II。)使用要替换的关键字:

读取模式打开文件,然后将内容复制到列表中

with open("some_file.txt","r") as f:
    newline=[]
    for word in f.readlines():        
        newline.append(word.replace("Warrior","Mage"))  ## Replace the keyword while you copy.  
Run Code Online (Sandbox Code Playgroud)

“战士”已由“法师”代替,因此将更新的数据写入文件:

with open("some_file.txt","w") as f:
    for line in newline:
        f.writelines(line)
Run Code Online (Sandbox Code Playgroud)

这是两种情况下的输出结果

Dan                   Dan           
Warrior   ------>     Mage       
500                   500           
1                     1   
0                     0           
Run Code Online (Sandbox Code Playgroud)