lennard743
lennard743

Reputation: 15

How can I replace in Python a specific number in a file?

I have a problem in python... I want to replace a number in a file but I don't know how. So for example I have these numbers in a file:

3
5
76
35
9

after I tried to replace the 5 with a 12, I will have this file

3
12
76
312
9

but I want to have every line as a seperet number, the correct file should look like this

3
12
76
35
9

I unfortunately have no plan how to do this. Does someone has an idea? This is my code:

def Wert_aendern():
   d = open("Datei.dat",'r')

   filedata = d.read()
   d.splitlines()
   d.close()
   a = input('Geben Sie bitte die zu ändernde Zahl ein')
   b = input('Geben Sie bitte die neue Zahl ein')
   newdata = filedata.replace(a, b)

   d = open("Datei.dat",'w')
   d.write(newdata)
   d.close()

Upvotes: 0

Views: 551

Answers (3)

Selim
Selim

Reputation: 131

To replace 35 with 312, you need to check if a row has desired string:

if a in line:

def Wert_aendern():
    with open("Datei.dat",'r') as f:
        filedata = f.read()

    a = str(input('Geben Sie bitte die zu ändernde Zahl ein'))
    b = str(input('Geben Sie bitte die neue Zahl ein'))

    file_values = filedata.split('\n')

    for idx, line in enumerate(file_values):
        if a in line:
           file_values[idx] = line.replace(a, b)

    with open("Datei.dat",'w') as f:
        f.write('\n'.join(file_values))
Wert_aendern()

Upvotes: 0

blhsing
blhsing

Reputation: 106608

If there is only one number per line in your input file as suggested by your example, you can simply match the entire line (after stripping the trailing newline character) against the number being searched for, and output the replacement string instead of the original line if they match.

Also note that it's better not to write directly back to the input file but instead write to a temporary file and then rename it to the input file to minimize the chance of data loss during the write-back due to interruption:

import os

with open('Datei.dat') as file, open('output.tmp', 'w') as output:
    a = input('Geben Sie bitte die zu ändernde Zahl ein')
    b = input('Geben Sie bitte die neue Zahl ein')
    for line in file:
        output.write(b + '\n' if line.rstrip('\n') == a else line)
os.rename('output.tmp', 'Datei.dat')

Upvotes: 1

Binh
Binh

Reputation: 1173

A little change from your code:

def Wert_aendern():
    with open('/Users/binhna/Downloads/text.txt', 'r') as f:
        d = f.readlines()
        d = [i.strip() for i in d]
    print(d)
    a = input('Geben Sie bitte die zu ändernde Zahl ein')
    b = input('Geben Sie bitte die neue Zahl ein')
    for i, x in enumerate(d):
        if x == a:
            d[i] = b
    print(d)
    #write d back to file

enter image description here

Upvotes: 1

Related Questions