473,549 Members | 3,109 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

search and replace in a text file and save the changes

16 New Member
I am trying to search for a pattern in a text file and replace with another string.
I've opened the file in "r+" mode and used re.sub for replacement text.

The python output window is showing the desired result, but when I open the text file there is no change. The string that is to be replaced is not replaced in the text file.

Why is it so?
Expand|Select|Wrap|Line Numbers
  1. # !/usr/bin/python
  2.  
  3. import os,re
  4.  
  5. fName = r'LOCATION OF FILE'
  6. directory = os.path.dirname(fName)
  7.  
  8. os.chdir(directory)
  9.  
  10. fileName = os.path.basename(fName)
  11. print(fileName)
  12. o_File = open(fileName ,"r+")
  13.  
  14. with o_File as readFile:    
  15.     for searchpattern in readFile:
  16.  
  17.         found_Pattern = re.search("\s*\'[\d]+\==*[\d]*\.*[\d]*\==*[\d]*\.*[\d]*\'*",searchpattern,re.IGNORECASE)
  18.         if found_Pattern:
  19.             found_Pattern_Pat = found_Pattern.group()
  20.             print(value)
  21.             fValue = re.sub(r'==(.+)==','==100==',found_Pattern_Pat)
  22.             print(fValue)
  23.  
  24. o_File.close()
Mar 14 '14 #1
3 1410
bvdet
2,851 Recognized Expert Moderator Specialist
Assuming your data file is not so large it cannot be stored in memory, compile a list of modified and unmodified lines of text (searchpattern would be one line of text). After closing o_File, open the file again or another suitable file in write mode and write the contents of the compiled list to it. Close the file object to flush the contents to disk.
Mar 14 '14 #2
nischalinn
16 New Member
@BVDET Thank you for the prompt reply.
Please can you tell me why I've to do so? In the tutorials, it is said that when you open a file in "r+" mode, the file is accessed in read as well as write mode.
But in my case, why it is not happening?
Please can you clarify me.

Thank You!
Mar 14 '14 #3
bvdet
2,851 Recognized Expert Moderator Specialist
OK, "r+" instead of "r" is for reading and writing, but you still have to write the updated text out to the file. It may work on a line by line basis - I'm not sure. Let us know how it turns out.
Mar 14 '14 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

11
8105
by: alex | last post by:
Hi, I am looking for a way to populate an HTML table from an external local text file which looks like this: DATE/TIME LAT. LON. DEPTH. ML. -------------------- ---------- ---------- ------- ------- 21/03/2005-04:06:03 XX,XX XX,XX 171 3,42 21/03/2005-12:23:53 XX,XX ...
3
1520
by: Josh | last post by:
I would like to search a text file on my server and then alert me on if the current date exist in that file. Any one have any code that searches text files. thanks in advance
4
2203
by: suzy | last post by:
hello, i want to search a text file for an occurrence of a string and replace some text after the match, then save the file. eg: if the file is: <start> Hello my name is tony, I am 22. Hello, my name is sonia, I am 18.
1
4386
by: Andrew | last post by:
Hi, im trying to create a small function which can create a binary tree from the entries in a text file and after that we can perform all the usual operations like search, insert and delete etc. Now i have entries something like this IPaddress Phone No 192.168.2.1 2223447689 192.168.2.2 3334449898 192.168.2.3 5667869089
1
1546
by: Prabhat | last post by:
Hello friends, I have one TEXT file that I use to log download information from website. The file will have unique Login ID for the downloads. When the user will come for next time for download the LOG entry should go under the same section (same ID number) so for this I need to search the text file for the ID and if the ID is found the...
13
4165
by: DH | last post by:
Hi, I'm trying to strip the html and other useless junk from a html page.. Id like to create something like an automated text editor, where it takes the keywords from a txt file and removes them from the html page (replace the words in the html page with blank space) I'm new to python and could use a little push in the right direction, any...
3
1505
by: mse07 | last post by:
hi all i search about statement in text file by this code : LineFlag = LineFlag + 1 Line Input #1, strLine If LineFlag = 15 Then If InStr(1, strLine, " Transfer completed successfully.") <> 0 Then MsgBox "successful"
8
2336
by: ImanMan | last post by:
hi Am using the following code to search a textfile.The returned value will always be found in this case, is there any problem in the code?? Dim list As System.Collections.ObjectModel.ReadOnlyCollection _ (Of String) list = My.Computer.FileSystem.FindInFiles("C:\Find", _ Search.Text, True,...
1
1173
by: ahmed222too | last post by:
i use vb6 i want to make a backword search in text file i mean (by backword search) to begin the search from the last for example (i will go to school to learn more....) i want to find the last time the word (to) happened then the next backwordly
1
1730
by: ogo796 | last post by:
Hi everyone i want to search the text file,using pregmatch() but it seems like it dose't serch.maybe my serching pattern is not right.look at the following code. Myfile look like this -------------------------------- file : (49/06/01) simon 13; file : (68/05/01) John 17 ; i want to serch simon 13 on the text file. can anyone...
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7718
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3480
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1058
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.