在 Python 中编辑文本文件中的特定行[重复]

2024-12-24 08:56:00
admin
原创
120
摘要:问题描述:假设我有一个包含以下内容的文本文件:Dan Warrior 500 1 0 有没有办法可以编辑该文本文件中的特定行?目前我有这个:#!/usr/bin/env python import io myfile = open('stats.txt', 'r') dan = myfile.readlin...

问题描述:

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

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('
')[0]

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

是的,我知道这myfile.writelines('Mage')[1]是错误的。但你明白我的意思,对吧?我正在尝试编辑第 2 行,将战士替换为法师。但我能做到吗?


解决方案 1:

你想做这样的事:

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

解决方案 2:

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

进而:

replace_line('stats.txt', 0, 'Mage')

解决方案 3:

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

import fileinput
for line in fileinput.FileInput("myfile", inplace=1):
    if line .....: # select which lines you care about
        print line

解决方案 4:

您可以通过两种方式进行操作,选择适合您要求的方式:

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

首先,在读取模式下获取变量中的所有数据

with open("your_file.txt",'r') as f:
    get_all=f.readlines()

第二,写入文件(枚举开始起作用的地方)

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
")
        else:
            f.writelines(line)

方法 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.  

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

with open("some_file.txt","w") as f:
    for line in newline:
        f.writelines(line)

两种情况下的输出如下:

Dan                   Dan           
Warrior   ------>     Mage       
500                   500           
1                     1   
0                     0           

解决方案 5:

如果您的文本仅包含一个人:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan 
 Warrior 
 500 
 1 
 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:
',repr(h.read())
with open('pers.txt','rU') as h:
    print '
rU-display of pers.txt before treatment:
',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^
]+[
]+)[^
]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '
exact content of pers.txt after treatment:
',repr(h.read())
with open('pers.txt','rU') as h:
    print '
rU-display of pers.txt after treatment:
',h.read()

如果您的文本包含多个个体:

进口再

# creation
with open('pers.txt','wb') as g:
    g.write('Dan 
 Warrior 
 500 
 1 
 0 
 Jim  
  dragonfly
300
2
10
Somo
cosmonaut
490
3
65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:
',repr(h.read())
with open('pers.txt','rU') as h:
    print '
rU-display of pers.txt before treatment:
',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^s*'+who+'s*[
]+([^
]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:
',repr(h.read())
with open('pers.txt','rU') as h:
    print '
rU-display of pers.txt after treatment:
',h.read()

如果某个人的“工作”在文本中的长度是恒定的,那么您只能将与所需个人的“工作”相对应的文本部分更改为:这与 senderle 的想法相同。

但在我看来,更好的办法是将个人的特征放入一个字典中,并用 cPickle 记录在文件中:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '
id_cards after change==',id_cards

解决方案 6:

今天晚上我一直在练习处理文件,意识到我可以基于 Jochen 的答案来提供更强大的重复/多次使用功能。不幸的是,我的答案没有解决处理大文件的问题,但确实让处理小文件变得更容易。

with open('filetochange.txt', 'r+') as foo:
    data = foo.readlines()                  #reads file as list
    pos = int(input("Which position in list to edit? "))-1  #list position to edit
    data.insert(pos, "more foo"+"
")           #inserts before item to edit
    x = data[pos+1]
    data.remove(x)                      #removes item to edit
    foo.seek(0)                     #seeks beginning of file
    for i in data:
        i.strip()                   #strips "
" from list items
        foo.write(str(i))

解决方案 7:

假设我有一个名为file_name如下的文件:

this is python
it is file handling
this is editing of line

我们必须将第 2 行替换为“修改完成”:

f=open("file_name","r+")
a=f.readlines()
for line in f:
   if line.startswith("rai"):
      p=a.index(line)
#so now we have the position of the line which to be modified
a[p]="modification is done"
f.seek(0)
f.truncate() #ersing all data from the file
f.close()
#so now we have an empty file and we will write the modified content now in the file
o=open("file_name","w")
for i in a:
   o.write(i)
o.close()
#now the modification is done in the file

解决方案 8:

写入初始数据,打印一个空值str以将其更新为新数据,我们str在代码的最后一行插入一个空值,此代码可用于交互式更新,换句话说,在文本.txt文件中附加数据

with open("data.txt", 'w') as f:
    f.write('first line
'
            'second line
'
            'third line
'
            'fourth line
'
            ' 
')

更新文本文件最后一行的数据

my_file=open('data.txt')
string_list = my_file.readlines()
string_list[-1] = "Edit the list of strings as desired
"
my_file = open("data.txt", "w")
new_file_contents = "". join(string_list)
my_file. write(new_file_contents)

解决方案 9:

我以前也有同样的要求,最后还是用了 Jinja 模板。将你的文本文件改为下面的样子,加上一个变量 lastname,然后你就可以通过传递来渲染模板了lastname='Meg',这是我能想到的最有效、最快捷的方法。

Dan 
{{ lastname }} 
Warrior 
500 
1 
0

解决方案 10:

#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson
'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

解决方案 11:

这是最简单的方法。

f = open("file.txt", "wt")
for line in f:
    f.write(line.replace('foo', 'bar'))
f.close()

我希望它对你有用。

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用