use*_*549 2 python io replace file
首先,因为我之前被断电的人烧伤过,所以这个问题不是家庭作业。
无论如何,我有一个类似于以下内容的文本文件:
####
# File section 1
####
1.0 abc Description1
6.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
####
# File section 2
####
1.0 abc Description1
12.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
#### End file
Run Code Online (Sandbox Code Playgroud)
我想替换两行中的字符串“1.0”:
1.0 abc Description1
Run Code Online (Sandbox Code Playgroud)
但是,不是以下行中的“1.0”字符串:
1.0 2.0 3.0 ghi Description3
Run Code Online (Sandbox Code Playgroud)
我当前使用的代码是:
with open('sample_file.txt','r') as file:
filedata = file.read()
filedata = filedata.replace('1.0','2.0')
with open('sample_file.txt','w') as file:
file.write(filedata)
Run Code Online (Sandbox Code Playgroud)
然而结果是所有出现的“1.0”都被替换。然后我必须返回文件并纠正错误。我想要得到的结果文件是:
####
# File section 1
####
2.0 abc Description1
6.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
####
# File section 2
####
2.0 abc Description1
12.5 def Description2
1.0 2.0 3.0 ghi Description3
11 jkl Description
#### End file
Run Code Online (Sandbox Code Playgroud)
我怎样才能得到它?我找不到此类问题的示例解决方案。感谢大家的帮助。
编辑:我的错误是没有澄清,但我想要替换的字符串并不总是“1.0”,也不总是 3 个字符长。例如,它可能是“-12.3”。我想让代码尽可能通用。
我还尝试使用 rsplit 使用空格作为分隔符来隔离第一个字符串,但这似乎不适用于文件写入。
=======================
EDIT2:我找到了一种方法来做到这一点,尽管它似乎是一个相当迂回的方法:
with open('sample_file.txt','r') as file:
filedata = file.readlines()
for line in filedata:
if 'abc' in line:
oriline = line
newline = line.replace(str(spk),str(newspk))
with open('sample_file.txt','r') as file:
filedata = file.read()
filedata = filedata.replace(str(oriline),str(newline))
with open('sample_file.txt','w') as file:
file.write(filedata)
Run Code Online (Sandbox Code Playgroud)
基本上,它会打开文件,逐行读取包含我想要的特定字符串的整行,然后将其存储到内存中。然后再次打开文件,读取所有内容,然后替换整个字符串。然后打开文件,并写入文件。
它满足了我的要求,但是有没有办法简化代码?
只需使用
with open('sample_file.txt','r') as file:
filedata = file.read()
filedata = filedata.replace('1.0 abc','2.0 abc')
with open('sample_file.txt','w') as file:
file.write(filedata)
Run Code Online (Sandbox Code Playgroud)
除了上面的快捷方式之外,您还可以通过首先定义一个空列表来尝试更通用的情况:
li = []
然后使用下面的代码(考虑到字符串abc是固定的,如上面的情况):
with open('sample_file.txt','r') as file:
for line in file:
i = line.find('abc',1)
if i >= 0:
lineval = line.replace('1.0','2.0')
li.append(lineval)
else:
lineval = line
li.append(lineval)
j = 0
with open('sample_file.txt','w') as file:
while j < len(li):
file.write(li[j])
j += 1
Run Code Online (Sandbox Code Playgroud)