简体   繁体   中英

Rewriting Single Words in a .txt with Python

I need to create a Database, using Python and a .txt file. Creating new items is no Problem,the inside of the Databse.txt looks like this:

Index Objektname Objektplace Username

ie:

1 Pen Office Daniel

2 Saw Shed Nic

6 Shovel Shed Evelyn

4 Knife Room6 Evelyn

I get the index from a QR-Scanner (OpenCV) and the other informations are gained via Tkinter Entrys and if an objekt is already saved in the Database, you should be able to rewrite Objektplace and Username . My Problems now are the following:

If I scan the Code with the index 6, how do i navigate to that entry, even if it's not in line 6, without causing a Problem with the Room6?

How do I, for example, only replace the "Shed" from Index 4 when that Objekt is moved to fe Room6? Same goes for the Usernames.

Up until now i've tried different methods, but nothing worked so far. The last try looked something like this

def DBChange():

        #Removes unwanted bits from the scanned code
        data2 = data.replace("'", "")
        Index = data2.replace("b","")

        #Gets the Data from the Entry-Widgets
        User = Nutzer.get()
        Einlagerungsort = Ort.get()

        #Adds a whitespace at the end of the Entrys to seperate them
        Userlen = len(User)
        User2 = User.ljust(Userlen)

        Einlagerungsortlen = len(Einlagerungsort)+1
        Einlagerungsort2 = Einlagerungsort.ljust(Einlagerungsortlen)

        #Navigate to the exact line of the scanned Index and replace the words
        #for the place and the user ONLY in this line

        file = open("Datenbank.txt","r+")               
        lines=file.readlines()

        for word in lines[Index].split():
            List.append(word)

        checkWords = (List[2],List[3])
        repWords = (Einlagerungsort2, User2)

        for line in file:
            for check, rep in zip(checkWords, repWords):
                line = line.replace(check, rep)
            file.write(line)

        file.close()

        Return()

Thanks in advance

I'd suggest using Pandas to read and write your textfile. That way you can just use the index to select the approriate line. And if there is no specific reason to use your text format, I would switch to csv for ease of use.

import pandas as pd

def DBChange():

    #Removes unwanted bits from the scanned code
    # I haven't changed this part, since I guess you need this for some input data
    data2 = data.replace("'", "")
    Indexnr = data2.replace("b","")

    #Gets the Data from the Entry-Widgets
    User = Nutzer.get()
    Einlagerungsort = Ort.get()

    # I removed the lines here. This isn't necessary when using csv and Pandas

    # read in the csv file
    df = pd.read_csv("Datenbank.csv")               

    # Select line with index and replace value
    df.loc[Indexnr, 'Username'] = User
    df.loc[Indexnr, 'Objektplace'] = Einlagerungsort

    # Write back to csv
    df.to_csv("Datenbank.csv")

    Return()

Since I can't reproduce your specific problem, I haven't tested it. But something like this should work.

Edit

To read and write text-file, use ' ' as the seperator. (I assume all values do not contain spaces, and your text file now uses 1 space between values).

reading:

df = pd.read_csv('Datenbank.txt', sep=' ')

Writing:

df.to_csv('Datenbank.txt', sep=' ')

First of all, this is a terrible way to store data. My suggestion is not particularily well code, don't do this in production! (edit

newlines = []
for line in lines:
  entry = line.split()
  if entry[0] == Index:
    #line now is the correct line
    #Index 2 is the place, index 0 the ID, etc
    entry[2] = Einlagerungsort2
  newlines.append(" ".join(entry))
# Now write newlines back to the file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM