-1

How to replace a specific line or a string with another string on a text file with Python? I tried this method:

with open("textfile.txt","r") as f:
    newline = []
    for word in f.readlines():        
        newline.append(word.replace("previous_line","new_line"))
hhh_
  • 310
  • 2
  • 5
  • 17
Itachi
  • 21
  • 6
  • I think you should refer to https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python – Pabasara Ranathunga Apr 02 '18 at 09:14
  • how to index the function to replace the next line for exaple we have line1 and line2 i want to replace the second line refering to line1 – Itachi Apr 02 '18 at 12:45
  • Possible duplicate of [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – Primusa Apr 08 '18 at 03:31

1 Answers1

0

Try below:

with open("test.txt", "r+") as f:
   data=f.read()

Now we have all the contents of a file in variable data , now assuming each line is ending with a \n . We can split it .

mylines = data.splitlines()
for x in range(1,len(mylines)-1):
    if myline[x]=='thanks for help':
       myline[x] = myline[x-1]
data = "\\n".join(mylines)
f.write(data)

of course, if the line replacing the thanks for help is not the previous line, u may need to create some logic there.

Rehan Azher
  • 1,340
  • 1
  • 9
  • 17
  • how to replace tho whole line without indicating strings into it , it means to replace (ANY) into this line – Itachi Apr 02 '18 at 12:40
  • Can u please explain more. What will be the reference where replace need to happen – Rehan Azher Apr 02 '18 at 12:40
  • for example i have line1:helloo world ; line2: thanks for help ; i want to remove line2 and replace it with other string refering to line1 it means i shold index my function with hello world for example – Itachi Apr 02 '18 at 12:48
  • sir how could i modify a variable with python for example i have a=test.c => a=test.h – Itachi Apr 02 '18 at 13:59
  • please explain more and if above explanation answer your question mark it as an answer. – Rehan Azher Apr 02 '18 at 14:00
  • i want to modify the extention of a file into a text file automatically from test.c to test.o – Itachi Apr 02 '18 at 14:07
  • if that is a file only `os.rename(srcfile,destinationfile)` but if u want to replace inside text u can simply use `data.replace(".c",".h")` or can use regex also. – Rehan Azher Apr 02 '18 at 14:09
  • how could i run a python script from a batch file ? – Itachi Apr 03 '18 at 08:26
  • please post a separte script for that . it is same as you execute other commands from batch file. `python scrpit.pl` – Rehan Azher Apr 03 '18 at 08:27
  • how to index the path in while loop 'while i<3: "\test\\ss\\tsss(i).inc" i +=1' – Itachi Apr 12 '18 at 17:17
  • please open a separate question, and also please explain more. not clear enough. – Rehan Azher Apr 12 '18 at 17:19