XpreSS
XpreSS

Reputation: 57

Replacing data in files with new inputs

First of all my program must work with several files and 10 inputs in every file, this is just little piece, to be clear.

My code right now:

code = input(">> ")
print("\nPress <Enter> and parameter will be same!")

f = open("komad_namestaja.txt", "r")
allDATA = f.readlines()
f.close()
for line in allDATA:
    lst = line.split("|")

    if code == lst[0]:

        print("\nName :", lst[1])
        name = input("New Name >> ")
        if name == "":
            name = lst[1]

        f = open("komad_namestaja.txt", "r")
        allDATA = f.read()
        f.close()
        newdata = allDATA.replace(lst[1], name)
        f = open("komad_namestaja.txt", "w")
        f.write(newdata)
        f.close()

        print("\ndestination :", lst[2])
        destination = input("New destination >> ")
        if destination == "":
            destination = lst[2]

        #Writting function here

File before:

312|chessburger|Denmark
621|chesscake|USA

code input: 312

name input: Gyros

destination input: Poland

file after inputs:

312|Gyros|Poland
621|chesscake|USA

Problem is this replacing in file I cant write 7 lines code every time, because I have 10 x 5 inputs, and also I tried everything and cant make function of this.

I must write some function for reading/writing/replacing or replacing all inputs after last one.

Upvotes: 1

Views: 61

Answers (1)

wkl
wkl

Reputation: 79903

You don't have to read the file in every time to modify one field, write it out, reopen it to change another field, and so on. That's inefficient, and in your case, causes code explosion.

Since your files are small, you could just read everything into memory at once and work on it in memory. Your code is easy to map via a dict.

Here's a function that takes a filename and converts your file into a dictionary.

def create_mapping(filename):
    with open(filename, 'r') as infile:
        data = infile.readlines()
        mapping = {int(k): (i,d) for k,i,d in 
                   (x.strip().split('|') for x in data)}
    # Your mapping now looks like
    # { 312: ('cheeseburger', 'Denmark'),
    #   621: ('chesscake', 'USA') }
    return mapping

Then you can update the mapping from user input since it's just a dictionary.

Once you want to write the file out, you can just serialize out your dictionary by iterating over the keys and rejoining all the elements using |.

If you want to use lists

If you want to stick with just using lists for everything, that is possible.

I would still recommend reading your file into a list, like so:

def load_file(filename):
    with open(filename, 'r') as infile:
        data = infile.readlines()
        items = [(int(k), i, d) for k,i,d in
                 (x.strip().split('|') for x in data]
        # Your list now looks like
        # [(312, 'cheeseburger', 'Denmark'), (621, 'chesscake', 'USA')]
    return items

Then when you get some user input, you have to traverse the list and find the tuple with what you want inside.

For example, say the user entered code 312, you could find the tuple that contained the 312 value from the list of tuples with this:

items = load_file(filename)

# Get input for 'code' from user
code = int(input(">> "))

# Get the position in the list where the item with this code is
try: 
    list_position = [item[0] for item in items].index(code)
    # Do whatever you need to (ask for more input?)
    # If you have to overwrite the element, just reassign its
    # position in the list with
    # items[list_position] = (code, blah, blah)
except IndexError:
    # This means that the user's entered code wasn't entered
    # Here you do what you need to (maybe add a new item to the list),
    # but I'm just going to pass
    pass

Upvotes: 1

Related Questions