简体   繁体   中英

How to search a string(say str1) and replace it with another string(say str2) in a file using python?

I have to search a string(say str1) in a file and replace it with another string(say str2) in that same file. The searching(of str1) and writing(of str2) of the 2 strings will be done on the same file. Please someone suggest some methods or logic for this.

The following code will do that task:

FILE = r'A:\some\sort\of\floppy\file.txt' # The target file.
str1 = '\n'
str2 = '\r\n'

data = ''

with open(FILE) as f: # Comment the "with" block under Python 2.6
    data = f.read()
# Uncomment lines below if the "with" statement is commented
##f = open(FILE)
##data = f.read()
##f.close()
data = data.replace(str1, str2)

with open(FILE, 'w') as f: # Same as for previous "with"
    f.write(data)
# And here too
##f = open(FILE)
##f.write(data)
##f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM