繁体   English   中英

如何清除文件python中的特定数据

[英]How to erase specific data in file python

我似乎无法在文件中写入每一行,因此它就像一个长字符串,例如:“ a,1; b,2; c,3”。 我想编写一个例如删除“ b,2”的方法。 另外,我不能用线条写它,这就是为什么我有点困惑和卡住...所有助手的想法。

class Data:

def __init__(self):

    print "are you ready?? :)"

def add_data(self, user_name, password):

    add = open("user_data.txt", "a")
    add.write(user_name + "," + password + ";")
    add.close()

def show_file(self):

    file = open("user_data.txt", "r")
    print file.read()
    file.close()

def erase_all(self):

    file = open("user_data.txt", "w")
    file.write("")
    file.close()

def return_names(self):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")
    names = []

    for data in users_data:

        data = data.split(",")
        names.append(data[0])

    file.close()
    return names

def is_signed(self, user_name):

    names = self.return_names()

    for name in names:

        if user_name == name:

            return True

    return False

def is_password(self, user_name, password):

    file = open("user_data.txt", "r")
    users_data = file.read()
    users_data = users_data.split(";")

    for data in users_data:

        data = data.split(",")

        if data[0] == user_name:

            if data[1] == password:

                return True

    file.close()

    return False

def erase_user(self, user_name):

    pass

如评论中所述,每次向文件中写入一行时,您都希望包含换行符。 只是一个建议,为了使文件处理更容易,您可能需要在每次访问文件时考虑将其与open()一起使用。

因此,例如,一类方法:

def add_data(self, user_name, password):
        with open('user_data.txt', 'a') as add:
            add.write(user_name + ',' + password + ';')
            add.write('\n') # <-- this is the important new line to include

    def show_file(self):
        with open('user_data.txt') as show:
            print show.readlines()

...和其他方法类似。

至于从文件中删除用户条目的方法:

# taken from https://stackoverflow.com/a/4710090/1248974
def erase_user(self, un, pw):
    with open('user_data.txt', 'r') as f:
        lines = f.readlines()

    with open('user_data.txt', 'w') as f:
        for line in lines:
            user_name, password = line.split(',')[0], line.split(',')[1].strip('\n').strip(';')
            if un != user_name and pw != password:
                f.write(','.join([user_name, password]))
                f.write(';\n')

测试:

d = Data()
d.erase_all()
d.add_data('a','1')
d.add_data('b','2')
d.add_data('c','3')
d.show_file()
d.erase_user('b','2')
print 'erasing a user...'
d.show_file()

输出:

are you ready?? :)
['a,1;\n', 'b,2;\n', 'c,3;\n']
erasing a user...
['a,1;\n', 'c,3;\n']

确认行条目已从文本文件中删除:

a,1;
c,3;

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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