Home > front end >  Is there a way to only replace a specific word in a specefic line and collumn in text file?
Is there a way to only replace a specific word in a specefic line and collumn in text file?

Time:09-07

So for example, this is the text file:

Product: Scissors, Price: $2, Stock: 50 

Product: Spoon, Price: $2, Stock: 35

Product: Spoon, Price: $2, Stock: 35

Product: Cheese, Price: $4, Stock: 100

The user would be able input which product's price/stock they want to modify. But how do I make it so that only the line of the product chosen will have their price/stock value changed? Or maybe there's a way to use lists to modify one single specific words instead?

f = open("C:/Users/--/OneDrive/Documents/python text files/Grocery.txt", "r ")
Search = input("What would you like to change: ")
Replace = input("What would you like to replace with: ")
data = f.read()
if Search in data:
    data = data.replace(Search, Replace)
    f.close()
    f = open("C:/Users/--/OneDrive/Documents/python text files/Grocery.txt", "r ")
    f.write(data)
    f.close()
    print("Information has been replaced!\n")

else:
    print("The information you searched for does not exists\n")

CodePudding user response:

My advice would be to create a *.ini file.
That is a file that contains values in multiple sections.
In your case the file would be something like this:

[scissors]
price = 2
stock = 50

[spoon]
price = 2
stock = 35

and so on...

To read or write in this file you can use the configparser library.
This is a useful YouTube video: link

CodePudding user response:

This will overwrite the file and replace it with your new desired output

with open("C:/Users/--/OneDrive/Documents/python text files/Grocery.txt", "r") as fr:
    Search = input("What would you like to change: ")
    Replace = input("What would you like to replace with: ")
    data = fr.read()
    if Search in data:
        data = data.replace(Search, Replace)
        with open("C:/Users/--/OneDrive/Documents/python text files/Grocery.txt", "w") as fw:
            fw.write(data)
        print("Information has been replaced!\n")

    else:
        print("The information you searched for does not exists\n")

If the Paranoid Android does not understand, he is free to say "what's that?" but he must sing it! ;)

CodePudding user response:

You probably want to separate the data from its representation (in your case a text file).

Your data should be saved as a Class, instance per product, with your required fields. Then you can hold your instances in a collection, let's say a dictionary, so you can access the products by name.

Then when you ask for input from your client - let her choose the product and field she wants to change, and change it.

After your data is updated, you can represent it as a text file, or write your whole collection to a text file.

There is an option to change parts of the file, but if your data is not that big, writing the whole representation should work.

  • Related