简体   繁体   中英

Trying to read/write to text file having trouble

I am trying to create and use a database for a chat program I have been working on. My chat program uses configparser and threads to load multiple clients. I am having trouble trying to get it to remove just one name from the list, it removes all names from the list when I attempt it. Also having a program with say I have name "P$Y|Omen" in the list, the program will not let me add just "P$Y" or "Omen" to the list. Is there a way to make sure it only checks for unique names on one line?

The database file is just a text document with each persons name on one line.

def remUser(self, sMsg):
    f = open('db.txt', 'r')
    lines = f.readlines()
    f.close()
    f = open('db.txt', 'w')
    for line in lines:
        if line != sMsg:
            f.write(line)
            self.send(sMsg + ' has been removed from the database.')
            return


def addUser(self, sMsg):
    def check(sMsg):
        with open('db.txt') as dataf:
            return any(sMsg in line for line in dataf)
    def write(sMsg):
        with open('db.txt', 'a') as database:
            database.write(sMsg + '\n')
    if check(sMsg):
        return
    else:
        write(sMsg)
        self.send(sMsg + " has been added to the database.")
        return


def hasAccess(self, sUsername):
    db = open('db.txt', 'r')
    for line in db:
        for name in line.split():
            if name ==  sUsername:
                return name
            else:
                pass

You chose very unefficient:

  1. type and method of storing data

  2. algorithm that does it.

I wrote my own chat in primary school and I used pickle module to keep info about users and messages.

from cPickle import load, dump

def addUser (name):
    f = open("users.pdc", "rb")
    users = load(f)
    f.close()
    if name in users:
        raise KeyError, "User %s already exists!" % name
    users.append(name)
    f = open("users.pdc", "wb")
    dump(users, f)
    f.close()

def remUser (name):
    f = open("users.pdc", "rb")
    users = load(f)
    f.close()
    try: users.remove(name)
    except: raise KeyError, "User %s does not exist!" % name
    f = open("users.pdc", "wb")
    dump(users, f)
    f.close()

def createfile ():
    f = open("users.pdc", "wb")
    dump([], f)
    f.close()

etc. etc.

This is handy because you can serialize practically any Python object, which means that you can put in as much structured data as you like.

If you want to keep your way it's OK, but filtering through for loop, and most definitely, writing to file line by line is not a way of doing this.

It will be slow. Lists already have methods you need, therefore after readlines() you can use list.remove().

Also, to write all back use either file.writelines() or file.write(str.join(list)).

But the best approach, with one file database, would be to use sqlite3. It is included in Python standard library.

The best thing about it is that you will be able to switch to some serious DBMS if you'll ever have to.

This way your chat will be efficient and won't kill the operating system and ruin your memory by writing over and over.

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