473,326 Members | 2,023 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Python to search text file string and replace it

20
Hi ,

i am in the middle of creating the script to match the string and replace it

in mount.txt
mickey:/work1 /work1 bla bla bla
mickey:/work2 /work2 bla bla bla
micket:/job /job bla bla bla


Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. import string
  3. s = open("/usr2/py/mount.txt","r+")
  4. for line in s.readlines():
  5.    print line
  6.    string.replace(line, 'mickey','minnie')
  7.    print line
  8. s.close()
  9.  
However, the string.replace seems not working, any advice??? Thank you!

I am using CentOS 4.6 and the python is 2.3.4
Jun 4 '09 #1
7 164318
bvdet
2,851 Expert Mod 2GB
Hello DannyMc,

string.replace() does not modify the argument string in place, but returns a modified string. You must make an assignment. Unless your file is very large, I would suggest updating the text in the file by reading the file, modifying the text, and writing the modified text back to the file. You can use string method replace() instead of importing the string module.
Expand|Select|Wrap|Line Numbers
  1. s = open("mount.txt").read()
  2. s = s.replace('mickey', 'minnie')
  3. f = open("mount.txt", 'w')
  4. f.write(s)
  5. f.close()
Jun 4 '09 #2
DannyMc
20
thanks for the solution bvdet!!
Jun 5 '09 #3
ghostdog74
511 Expert 256MB
you can use fileinput for inplace editing
Expand|Select|Wrap|Line Numbers
  1. import fileinput
  2. for line in fileinput.FileInput("file", inplace=1):
  3.     line=line.replace("old","new")
  4.     print line
  5.  
Jun 11 '09 #4
DannyMc
20
Hi guys, i managed to solve my problem with the following scripts:

Expand|Select|Wrap|Line Numbers
  1. #!/usr/bin/python
  2. import re
  3. #fstab location, use w mode as need to overwrite whole file.
  4. s = open("/usr2/py/mount.txt","r")
  5. #temp txt file to store new mount.
  6. tmpfile = open("/usr2/py/tmp.txt","a")
  7. #new nas mount point
  8. newmount = open("/usr2/py/newmount.txt","r")
  9. #search pg-swnas1 line
  10. for line in s.readlines():
  11.     if re.search("filer", line, re.IGNORECASE) != None:
  12.         print line
  13.     else:
  14.         tmpfile.write(line)
  15. #read the latest mount point
  16. readmount = newmount.read()
  17. #append to temp file
  18. tmpfile.write(readmount)
  19. s.close()
  20. tmpfile.close()
  21. tmpfile = open("/usr2/py/tmp.txt","r")
  22. readtmp = tmpfile.read()
  23. s = open("/usr2/py/mount.txt","w")
  24. s.write(readtmp)
  25.  
  26. tmpfile.close()
  27. newmount.close()
  28.  
  29.  
Though the code works, but it seems not a clean code. Is there anyway to simplify it???
Jun 25 '09 #5
bvdet
2,851 Expert Mod 2GB
I am a bit unclear about what mount.txt and newmount.txt contain and what you need to replace. You do not need re. You can test for membership with the in operator. If I understand correctly, this should work (untested):
Expand|Select|Wrap|Line Numbers
  1. mountList = open("/usr2/py/mount.txt", "r").readlines()
  2. newmountList = open("/usr2/py/newmount.txt","r").readlines()
  3. outputList = [item for item in mountList if "filer" not in item.lower()]
  4. outputList.extend(newmountList)
  5. f = open("/usr2/py/mount.txt","w")
  6. f.write(''.join(outputList))
  7. f.close()
Jun 25 '09 #6
Works nice, thanks !
Aug 9 '17 #7
hi bvdet,

The script works fine for single file but how can i replace for multiple files in a directory .

could you write the script please .
My file extensions are .xlf
folder c:/mrit/

with kind regards,
MJ
Nov 4 '18 #8

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

Similar topics

60
by: Julie | last post by:
What is the *fastest* way in .NET to search large on-disk text files (100+ MB) for a given string. The files are unindexed and unsorted, and for the purposes of my immediate requirements, can't...
6
by: thorpk | last post by:
I have an access database that i have added a pop up calendar to, the Table information for the Date Reported field is Date/Time format short date, input mask is 00/00/0000. i have created a...
0
by: fh217 | last post by:
Hi, Is there a way in Access to retrieve data in a specific area of a text file? The data ( a 6 character date in YYMMDD format ) always resides on the second line in positions 11 to 16. Thank...
1
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.