I am having trouble finding the answer to this after quite a bit of searching. What I want to do is, do a string search and write on the line above or below it, depending on my string.
Here is something I've done so far:
file = open('input.txt', 'r+')
f = enumerate(file)
for num, line in f:
if 'string' in line:
linewrite = num - 1
???????
EDIT EXTENSION OF INITIAL QUESTION: I already picked the answer that best solved my initial question. But now using Ashwini's method where I rewrote the file, how can I do a search AND REPLACE a string. To be more specific.
I have a text file with
SAMPLE
AB
CD
..
TYPES
AB
QP
PO
..
RUNS
AB
DE
ZY
I want to replace AB with XX, ONLY UNDER lines SAMPLE and RUNS
I've already tried multiple ways of using replace(). I tried something like
if 'SAMPLE' in line:
f1.write(line.replace('testsample', 'XX'))
if 'RUNS' in line:
f1.write(line.replace('testsample', 'XX'))
and that didn't work
The following can be used as a template:
import fileinput
for line in fileinput.input('somefile', inplace=True):
if 'something' in line:
print 'this goes before the line'
print line,
print 'this goes after the line'
else:
print line, # just print the line anyway
You may have to read all the lines in a list first, and if the condition is matched you can then store your string at a particular index using list.insert
with open('input.txt', 'r+') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if 'string' in line:
lines.insert(i,"somedata") # inserts "somedata" above the current line
f.truncate(0) # truncates the file
f.seek(0) # moves the pointer to the start of the file
f.writelines(lines) # write the new data to the file
or without storing all the lines you'll need a temporary file to store the data, and then rename the temporary file to the original file:
import os
with open('input.txt', 'r') as f, open("new_file",'w') as f1:
for line in f:
if 'string' in line:
f1.write("somedate\n") # Move f1.write(line) above, to write above instead
f1.write(line)
os.remove('input.txt') # For windows only
os.rename("newfile", 'input.txt') # Rename the new file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With