【问题标题】:How to erase specific data in file python如何擦除文件python中的特定数据
【发布时间】:2017-06-08 05:16:26
【问题描述】:

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

【问题讨论】:

  • add.write(... 的末尾添加'\n' 以开始新行。

标签: python file


【解决方案1】:

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    相关资源
    最近更新 更多