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

时间:2017-06-07 01:42:05

标签: python file

我似乎无法在文件中写出每一行,所以它像一个长字符串,如: “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

1 个答案:

答案 0 :(得分:1)

正如评论中所提到的,每次向文件写入一行时,您都希望包含换行符。 只是一个建议,为了使文件处理更容易,您可能需要考虑每次访问文件时使用with 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;

希望这有帮助。