To start off, because I've been burned before by someone with a power trip, this question is not for homework.
Anyway, I have a text file that is something like the following:
####
# 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
I would like to replace the string "1.0" in the 2 lines:
1.0 abc Description1
However, NOT the "1.0" string in the lines:
1.0 2.0 3.0 ghi Description3
The current code that I'm using is:
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)
However the result is that all occurrences of "1.0" get replaced. Then I have to go back into the file, and correct the bug. The resultant file that I would like to get is:
####
# 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
How can I get that? I couldn't find an example solution to this type of issue. Thank you all for your help.
EDIT: My fault for not clarifying, but the string I want to replace isn't always "1.0", nor always 3 characters long. It could be "-12.3", for example. I would like to make the code as generic as possible.
I also tried using rsplit to isolate the first string using space as a delimiter, but that doesn't seem to work for file writing.
========================
EDIT2: I found a way to do this, though it seems to be quite a round-about method:
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)
Basically, it would open the file, read line by line for the whole line that contains the specific string I want, then just store it into memory. Then open the file again, read everything, and just replace that whole string. Then open the file, and write the file.
It does what I want, but is there a way to simplify the code?
filedatain place and then usefile.writelinesonfiledata. Also, there is only oneoriline, so if "abc" appears twice in the same file (like in your example), it won't work. Additionally, you will perform a replacement if "abc" appears anywhere in the line (including the description) and will replace all occurrences ofspkwithnewspk(whatever those are), not just in the first token. You also states that the string-to-be-replaced isn't a fixed string, which your approach doesn't handle.