Text in a file replaced by regex. How to write the change into file?

python replace string in file regex
sed replace string in file
how to search and replace text in a file using python
awk replace string in file
sed replace regex
intellij find and replace regular expression
sed replace string in file with variable
sed replace string in multiple files

I can change the text in a file line by line, but I don't know how to write the results (changes) into the file.

This is a small part of my file:

<name>2016-09-15_obere-firstalm_gehen-6,5km</name>
<extensions>
    <line xmlns="http://www.topografix.com/GPX/gpx_style/0/2">
        <color>000000</color>
    </line>
</extensions>
<trkseg>
    <trkpt lat="47.671193" lon="11.886518">
        <ele>1115.6</ele>
        <time>2016-09-15T11:57:44Z</time>
    </trkpt>
    <trkpt lat="47.670686" lon="11.886412">
        <ele>1117.6</ele>
        <time>2016-09-15T11:58:14Z</time>
    </trkpt>
    <trkpt lat="47.670821" lon="11.886459">
        <ele>1055.6</ele>
        <time>2016-09-15T11:58:44Z</time>
    </trkpt>

With a Python script I change values of elevations by adding 30. Example: Before change: elevation (ele) 1115.6, after change: elevation (ele) 1145.6

#This little Python adds 30 to elevation:
import re
f1 = raw_input("name of your GPX file: ")
f1 = open(f1,'r+')
for line in f1:
res = re.search(r"<(ele)>(.+)</\1>",line)
if res:
    number=float(res.group(2))
    number_elev=number+30
    number_elev=str(number_elev)
    ress = re.sub(r"<(ele)>(.+)", r"\2",number_elev)
    #print shows correct new values between <ele> and </ele>
    print ress + "\n"
    ###but how to write into the gpx file these changes?
f1.close()
print "OK"

Expected: Write the file with the changed lines. Actual: I don't know how to write a change by regexp into the file. Thx in advance for your help.

You'll first need to read all the lines in your file and write each one to the file replacing the ones matching the regex search. Also since one more <ele>..</ele> tag sequences can be on the same line, you'll need to find all occurrences of those in the line and replace them accordingly.

import re
f1 = raw_input("name of your GPX file: ")
with open(f1,'r') as f:
    lines = f.readlines()
with open(f1, 'w') as f:
    for line in lines:
        ress = line
        res = re.findall(r"<(ele)>(.+)</\1>",ress)
        if res:
            for r in res:
                number=float(r[1])
                number_elev=number+30
                number_elev=str(number_elev)
                ress=re.sub(r"<(ele)>{}</(ele)>".format(r[1]), r"<ele>{}</ele>".format(number_elev),string=ress, count=1)
        f.write(ress)

How to update and replace text in a file in Python, Retrieve the file contents with file.read() and call re.sub(pattern, replace, string) to replace the selected regular expression pattern with replace in the provided string Use file.write(text) to insert the new text with the replaced words into the file. Below is an example of a function I built called Find-InTextFile which uses this approach combined with the ability to find (not replace) text in a file. This function also uses the more powerful regular expression syntax to find strings as well.

Don't try to read and write from/to the same file at the same time. Just create and output file and write to it.

The following code is untested but it should work.

import re
f1 = input("name of your GPX file: ")
input_file = open(f1,'r+')
output_file = open(f1 + '_output', 'w+')
for line in input_file:
    res = re.search(r"<(ele)>(.+)</\1>", line)
    if res:
        number=float(res.group(2))
        number_elev=number+30
        number_elev=str(number_elev)
        line = line.replace(res.group(2), number_elev)
    output_file.write(line)
input_file.close()
output_file.close()
print("OK")

How to Use sed to Find and Replace String in Files, With sed you can search, find and replace, insert, and delete strings and lines. It supports basic and extended regular expressions that allow you to Quite often when working with text files you'll need to find and replace strings of text in It is a good practice to put quotes around the argument so the shell  If an extension is supplied (ex -i.bak) a backup of the original file will be created. s - The substitute command, probably the most used command in sed. / / / - Delimiter character. It can be any character but usually the slash (/) character is used. SEARCH_REGEX - Normal string or a regular expression to search for. REPLACEMENT - The replacement string.

You can read the file all at once and apply the regex to the data and write out the modified data to another file as follows:

import re

with open('input-file.xml') as fd:
    data = fd.read()

regex = re.compile('(<ele>)([\d.]+)(</ele>)')
while True:
    match = regex.search(data)
    if not match:
        break
    new_value = float(match.group(2)) + 30
    # <ele>6373.8</ele> becomes </ele>6373.8<ele> so that it doesnt match again
    data = regex.sub(r'\g<3>{}\g<1>'.format(new_value), data, count=1)

# undo </ele>...<ele> the tag reversal done inside the while loop
regex = re.compile('(</ele>)([\d.]+)(<ele>)')
data = regex.sub(r'\3\2\1', data)

with open('output-file.xml', 'w') as fd:
    fd.write(data)

Find and replace text using regular expressions, If you need to search and replace in more than one file, press Ctrl+Shift+R . For more Ctrl+V ) it in the search field, the regex symbols will not be taken into account. For example, if you want to search for only uppercase characters, type the  Applications almost never 'change something in a file'. They replace the old file with a new file. There are two ways to go here: 1: You read the entire file into memory, close the file handle, manipulate the data, and then overwrite the file. 2: You write out all lines from the old file (both the original and changed ones) to a temporary file and at the end delete the input file and rename

Find and replace text using regular expressions, If you need to search and replace in more than one file, press Ctrl+Shift+R . paste ( Ctrl+V ) it in the search field, the regex symbols will not be taken into account. For example, if you want to search for only uppercase characters, type the  sed -i 's+regex+new-text+g' file.txt The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2. Examples that use sed to find and replace

How To Replace Text in a File with PowerShell -- Microsoft Certified , In this text file, I'd like to replace the word "brown" with "white. To make that happen, we'll use PowerShell's replace operator. with the replace operator to find complex strings, use regular expression groups and a whole lot more. Catch up on Adam's articles at adamtheautomator.com, connect on  The File by name entered by user is opened in read mode. The line number of the line to be replaced is asked as input. Next the data to be replaced is asked. A new file is opened in write mode named "copy.c". Now the contents of original file are transferred into new file and the line to be modified is deleted.

JavaScript: The Missing Manual: The Missing Manual, POWER USERS' CLINIC Using Subpatterns to Replace Text The replace() if you also want to put other formatted dates like 10 28 2008 or 10-28-2008 into the sample regular expressions in the example_ regex.txt file that accompanies the​  Search file for line containing "32916223", go to the 16th token where delims are "," and replace whatever is there with "13". Then re-write the line or just add the 13 in the correct position. Also, I need to have this accept user input and loop until user is done. The complete script I have is:

Comments
  • Have you tried to google about how to write to file in Python?
  • Applications almost never 'change something in a file'. They replace the old file with a new file. There are two ways to go here: 1: You read the entire file into memory, close the file handle, manipulate the data, and then overwrite the file. 2: You write out all lines from the old file (both the original and changed ones) to a temporary file and at the end delete the input file and rename the temporary file to the name of the inputfile.
  • You can use Python libraries that works with XML, it is a better solution than using re library.
  • It runs ok. I only revised two little things: two different files for read and write, and in the line next to last: </ele> instead of <\ele> Thank you very much !
  • It runs ok, too. I changed only a little bit: f1=raw_input(...........) Thank you very much !
  • It runs ok, too. Thank you very much !