How to replace all instances of a string in text file with Python 3? - string

I am trying to replace all instances of a given string in a text file. I am trying to read the file line by line and then use the replace function, however it is just outputting a blank file instead of the expected. What could I be doing wrong?
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")
fopen = open(file, 'r+')
lines = []
for line in fopen:
line = line.replace(remove,"")
fopen.close()

Try this:
# Make sure this is the valid path to your file
file = input("Enter a filename: ")
remove = input("Enter the string to be removed: ")
# Read in the file
with open(file, "r") as file:
filedata = file.read()
# Replace the target string
filedata = filedata.replace(remove, "")
# Write the file out again
with open(file, "w") as file:
file.write(filedata)
Note: You might want to use with open syntax, the benefit is elaborated in this answer by Jason Sundram.

Related

using python to parse through files for data

I have two files one template file and one file which has the values for the template file. I am trying to take the template file and then pass values to the variables from another file and combine the two into a third file. I am able to copy one file to another using the following snippet of code
`
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
fileHandle = open(sFile, "r")
texts = fileHandle.readlines()
fileHandle.close()
fileHandle = open(tFile, "w")
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("\nFile Copied Successfully!")
`
however I am not sure how to do it for two or more files and then to make them into one file. Any help/guidance is appreciated
This is certainly not the most elegant solution but I think it should work for you.
# You could add as many files to this list as you want.
list_of_files = []
count = 1
while True:
print(f"Enter the Name of Source File{count} (Enter blank when done adding files): ")
sFile = input()
# If the input is not empty then add the filename to list_of_files.
if sFile:
list_of_files.append(sFile)
count += 1
else:
break
print("Enter the Name of Target File: ")
tFile = input()
# With open will open the file and then close if when done.
with open(tFile, 'a+') as target:
# This will loop over all the files in your list.
for file in list_of_files:
tmp = open(file, 'r')
target.write('\n' + tmp.read())
tmp.close()

search and replace using a file for computer name

I've got to search for the computer name and replace this with another name in python. These are stored in a file seperated by a space.
xerox fj1336
mongodb gocv1344
ec2-hab-223 telephone24
I know this can be done in linux using a simple while loop.
What I've tried is
#input file
fin = open("comp_name.txt", "rt")
#output file to write the result to
fout = open("comp_name.txt", "wt")
#for each line in the input file
for line in fin:
#read replace the string and write to output file
fout.write(line.replace('xerox ', 'fj1336'))
#close input and output files
fin.close()
fout.close()
But the output don't really work and if it did it would only replace the one line.
u can try this way:
with open('comp_name.txt', 'r+') as file:
content = file.readlines()
for i, line in enumerate(content):
content[i] = line.replace('xerox', 'fj1336')
file.seek(0)
print(str(content))
file.writelines(content)

How to replace multiple strings in a file that are both lowercase as well as capitalized?

I am trying to read and replace all occurring strings within a file. Most are lowercase but there is one that is capitalized. How to a read the file so that regardless of the capitalization all strings are removed.
For reference this is the text I would like to edit and the word I would like to replace is "morning/Morning".
Text below:
"Good morning! / I was going to say you good morning / Good Afternoon Morning is when the sun comes up / I will call you in the morning"
See code below:
filename = input("Enter the filename: ")
stringToRemove = input("Enter the string to be removed: ")
infile = open(filename, 'r')
fileString = infile.read()
fileString = fileString.replace(stringToRemove, '')
infile.close()
outfile = open(filename, 'w')
outfile.write(fileString)
outfile.close()
print("Done")
You could use re.sub in case insensitive mode:
filename = input("Enter the filename: ")
stringToRemove = input("Enter the string to be removed: ")
infile = open(filename, 'r')
fileString = infile.read()
fileString = re.sub(r'\s*' + stringToRemove + r'\s*', ' ', fileString, flags=re.IGNORECASE).strip()
The output from your sample string here would be:
Good ! / I was going to say you good / Good Afternoon is when the sun comes up / I will call you in the

How to edit a line in a notepad file using python

I am trying to edit a specific line of a notepad file using Python 3. I can read from any part of the file and write to the end of it, however whenever I have tried editing a specific line, I am given the error message 'TypeError: 'int' object is not subscriptable'. Does anybody know how I could fix this?
#(This was my first attempt)
f = open('NotepadTester.txt', 'w')
Edit = input('Enter corrected data')
Line = int(input('Which line do you want to edit?'))
f.write(Edit)[Line-1]
f.close()
main()
#(This was my second attempt)
f = open('NotepadTester.txt', 'w')
Line = int(input('Which line do you want to edit?'))
Edit = input('Enter corrected data')
f[Line-1] = (Edit)
main()
you can't directly 'edit' a line in a text file as far as I know. what you could do is read the source file src to a variable data line-by-line, edit the respective line and write the edited variable to another file (or overwrite the input file) dst.
EX:
# load information
with open(src, 'r') as fobj:
data = fobj.readlines() # list with one element for each text file line
# replace line with some new info at index ix
data[ix] = 'some new info\n'
# write updated information
with open(dst, 'w') as fobj:
fobj.writelines(data)
...or nice and short (thanks to Aivar Paalberg for the suggestion), overwriting the input file (using open with r+):
with open(src, 'r+') as fobj:
data = fobj.readlines()
data[ix] = 'some new info\n'
fobj.seek(0) # reset file pointer...
fobj.writelines(data)
You should probably load all the lines into memory first, modify it from there, and then write the whole thing to a file.
f = open('NotepadTester.txt', 'r')
lines = f.readlines()
f.close()
Which_Line = int(input('Which line do you want to edit? '))
Edit = input('Enter corrected data: ')
f = open("NotepadTester.txt",'w')
for i,line in enumerate(lines):
if i == Which_Line:
f.writelines(str(Edit)+"\n")
else:
f.writelines(line)
f.close()

Find string and replace line

I already could get a lot of my code together (although it is not a long code). However i am struggeling to achieve the "replace the whole line and not only the search term". Is there like a symbol you can place to do that? Like: * or % etc.
import glob
for files in glob.glob("./prtr/*p*"):
with open(files, 'r') as file:
filedata = file.read()
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
with open(files, 'w') as file:
file.write(filedata)
It works so far that "TCPOPTS" is replaced with "TCPOPTS = 80" and a linebreak is done. But it is not deleting the rest of that line but just moves it to the next line. Which is of course correct due the code. So as mentioned all i need now is to have it not replace the search term but the whole line containing that search term.
Any advice is highly apreciated :)
Kind regards
Edit:
Before:
TCPOPTS = 90
Afterwards:
TCPOPTS = 80
= 90
Expected:
TCPOPTS = 80
I recently solved a very similar task in the following way:
# Scan file
with open(filePath, 'r') as file:
fileContent = file.readlines()
# Find line, where modification should be done
for lineIndex in range(len(fileContent)):
if ('TCPOPTS' in fileContent[lineIndex]):
fileContent[lineIndex] = 'TCPOPTS = 80\n'
with open(filePath, 'w') as tableFile:
tableFile.writelines(fileContent)
break
The benefit of doing it this way is, that the file is not rewritten, if your keyword is not found.
Try using str.startswith
Ex:
import glob
for files in glob.glob("./prtr/*p*"):
res = []
with open(files) as infile:
for line in infile: #Iterate Each line
if line.startswith("TCPOPTS"): #Check if TCPOPTS in line
res.append("TCPOPTS = 80\n")
else:
res.append(line)
with open(files, "w") as outfile: #Write back to file.
for line in res:
outfile.write(line)
You can use re.sub (after importing re) to match the whole line and use back-references to preserve selective portions of the match:
Change:
filedata = filedata.replace('TCPOPTS', 'TCPOPTS = 80\n')
to:
filedata = re.sub(r'^(?P<header>TCPOPTS\s*=\s*).*', r'\g<header>80', filedata, flags=re.MULTILINE)

Resources