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.
Asked
Active
Viewed 91 times
-4
-
i'm kind of sure this is duplicated... not sure how to prove it now... btw what did you try? – Oct 14 '17 at 08:07
-
Did you Google "search and replace string in file python" before asking? – Martin Smith Oct 14 '17 at 08:08
-
1Possible duplicate of [replacing text in a file with Python](https://stackoverflow.com/questions/13089234/replacing-text-in-a-file-with-python) – Martin Smith Oct 14 '17 at 08:08
-
Also possible duplicate of [Python: search for a STR1 in a line and replace the whole line with STR2](https://stackoverflow.com/questions/38313182/python-search-for-a-str1-in-a-line-and-replace-the-whole-line-with-str2) – Oct 14 '17 at 08:10
-
Your question is rather broad in its current state. It would be good if you posted some code that you've written, and ask a specific question about it. But I will mention that the usual practice is to _not_ modify the original file, but to make a new file, and delete the old one (if necessary) once the new file is saved. Otherwise, you risk losing your data if something bad happens, eg loss of power. – PM 2Ring Oct 14 '17 at 08:25
1 Answers
0
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()

Kotauskas
- 1,239
- 11
- 31