Search and replace a line in a file in Python
I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:
from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove
def replace(file_path, pattern, subst):
#Create temp file
fh, abs_path = mkstemp()
with fdopen(fh,'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
new_file.write(line.replace(pattern, subst))
#Copy the file permissions from the old file to the new file
copymode(file_path, abs_path)
#Remove original file
remove(file_path)
#Move new file
move(abs_path, file_path)
Search and replace lines in a file in python
with open('Text.txt','r') as f:
file_data = f.readlines()
i=0
while i in range(len(file_data)):
for line in file_data:
if file_data[i].lstrip().startswith('if') and ('|' in line):
file_data[i]= file_data[i].replace(' | ', ' || ')
i+=1
file_data_str = ''.join(file_data)
with open('Text.txt','w') as f:
f.write(file_data_str)
This should work.
Fastest way to find and replace specific line in a large text file with Python
I assume your memory can store the whole file. This should be faster by using regex:
import re
number = 407597693
with open("numbers.txt", "r") as f:
data = f.read()
# data = re.sub(f'({number}):(.*)', lambda x:f"{x.group(1)}:{float(x.group(2))+3600}", data)
data = re.sub("^" + str(number) + ".*\n", str(number) + ":" + str(int(time.time()) + 3600) + "\n", data, flags=re.MULTILINE)
with open("numbers.txt", "w") as f:
f.write(data)
Python: replace line in file starting with a pattern
You don't need to know what old
is; just redefine the entire line:
import sys
import fileinput
for line in fileinput.input([filename], inplace=True):
if line.strip().startswith('initial_mass = '):
line = 'initial_mass = 123\n'
sys.stdout.write(line)
How to find and replace a line in a text file?
This is a lot easier when you configure your text file to be key:value pairs (like the dict
construct in python, or values in another DB like SQL). Then you can simply set a sentinel value when the value is met, then unset when you've replaced the correct line.
So, if changing the format of text to:
ProductCode <value>
ProductName <value>
Price <value>
CurrentStock <value>
ReorderStock <value>
Targetstock <value>
Then you can do something like this:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0
with open('myDB.txt', 'r+') as database:
for line in database:
(key, val) = line.split()
if key == "ProductCode":
if val == ProductCode:
SentinelValue = 1
if key != "ProductCode":
if key == "CurrentStock":
if SentinelValue == 1:
line = line.replace(val, NewStock)
print line
It is a bit dirty and could surely be cleaned up, but it is much more verbose. Also, note that the space is important as it is used as the delimiter when splitting the lines.
You may also notice I didn't write to the file: At least for me in python 2.7, there seems to be an issue where I can't replace a line of text, only append with f.write()
. This code works and replaces to stdout, the workaround for writing to a file is to simply write all lines to a new file:
ProductCode = "28273139"
NewStock = "29"
SentinelValue = 0
fout = open('newDB.txt', 'w')
with open('myDB.txt', 'r+') as database:
for line in database:
(key, val) = line.split()
if key == "ProductCode":
if val == ProductCode:
SentinelValue = 1
if key != "ProductCode":
if key == "CurrentStock":
if SentinelValue == 1:
line = line.replace(val, NewStock)
fout.write(line)
print line
You could then write logic to replace the files as needed. However, I would very much suggest looking at how to write and read from an actual SQL database. I hope this helps! ^^
Search the word, and replace the whole line containing the word in a file in Python using fileinput
I realized that I was wrong by just an indentation. In the code piece 1 mentioned in the question, if I am bringing the 'print line,' from the scope of if i.e. if i outdent it, then this is solved...
As this line was inside the scope of if
, hence, only this new_text
was being written to the file, and other lines were not being written, and hence the file was left with only the new_text
. So, the code piece should be as follow :-
text = "mov9 = " # if any line contains this text, I want to modify the whole line.
new_text = "mov9 = Alice in Wonderland"
x = fileinput.input(files="C:\Users\Admin\Desktop\DeletedMovies.txt", inplace=1)
for line in x:
if text in line:
line = new_text
print line,
x.close()
Also, the second solution given by Rolf of Saxony & the first solution by Padraic Cunningham is somehow similar.
Replace only first line of text file in python
You can use the readlines and writelines to do this.
For example, I created a file called "test.txt" that contains two lines (in Out[3]). After opening the file, I can use f.readlines() to get all lines in a list of string format. Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.
with open("test.txt") as f:
lines = f.readlines()
lines # ['This is the first line.\n', 'This is the second line.\n']
lines[0] = "This is the line that's replaced.\n"
lines # ["This is the line that's replaced.\n", 'This is the second line.\n']
with open("test.txt", "w") as f:
f.writelines(lines)
Related Topics
Swap First and Last Digits of a Number( Using Loops)
Create a New Dataframe Based on Rows With a Certain Value
How to Get the Neighboring Elements in a Numpy Array With Taking Boundaries into Account
Python Key Error=0 - Can't Find Dict Error in Code
Why Is Python No Longer Waiting for Os.System to Finish
Access Is Denied When Trying to Pip Install a Package on Windows
Add Missing Dates to Pandas Dataframe
Drop Non-Numeric Columns from a Pandas Dataframe
How to Maximize a Plt.Show() Window Using Python
Pandas Groupby Columns With Nan (Missing) Values
Calculate Angle (Clockwise) Between Two Points
Python - Ensuring a Variable Holds a Positive Number
Algorithm for Distributing a Number Between Certain Number of Chunks