如何同时访问一个文件来添加/编辑/删除数据?

发布于 2024-12-27 19:13:38 字数 60 浏览 1 评论 0原文

我想创建一个文本文件并向其中逐行添加数据。如果文件中已存在数据行,则应将其忽略。否则,应将其附加到文件中。

I want to create a text file and add data to it, line by line. If a data line already exists in the file, it should be ignored. Otherwise, it should be appended to the file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

半窗疏影 2025-01-03 19:13:38

几乎可以肯定,您最好阅读该文件并编写新的更改版本。在大多数情况下,它会更快、更容易、更不容易出错并且更具可扩展性。

You are almost certainly better to read the file and write a new changed version. In most circumstances it will be quicker, easier, less error-prone and more extensible.

晌融 2025-01-03 19:13:38

如果你的文件不是那么大,你可以这样做:

added = set()

def add_line(line):
    if line not in added:
        f = open('myfile.txt', 'a')
        f.write(line + '\n')
        added.add(line)
        f.close()

但是,如果你必须担心并发性、文件中存储的大量数据,或者基本上除了快速处理之外的任何事情,这不是一个好主意和一次性的。

If your file isn't that big, you could just do something like this:

added = set()

def add_line(line):
    if line not in added:
        f = open('myfile.txt', 'a')
        f.write(line + '\n')
        added.add(line)
        f.close()

But this isn't a great idea if you have to worry about concurrency, large amounts of data being stored in the file, or basically anything other than something quick and one-off.

煞人兵器 2025-01-03 19:13:38

我是这样做的,

def retrieveFileData():
    """Retrieve Location/Upstream data from files"""
    lines = set()
    for line in open(LOCATION_FILE):
        lines.add(line.strip())
    return lines

def add_line(line):
    """Add new entry to file"""
    f = open(LOCATION_FILE, 'a')
    lines = retrieveFileData()
    print lines
    if line not in lines:
        f.write(line + '\n')
        lines.add(line)
        f.close()
    else:
        print "entry already exists"

if __name__ == "__main__":
    while True:
        line = raw_input("Enter line manually: ")
        add_line(line)
        if line == 'quit':
            break

I did it like this,

def retrieveFileData():
    """Retrieve Location/Upstream data from files"""
    lines = set()
    for line in open(LOCATION_FILE):
        lines.add(line.strip())
    return lines

def add_line(line):
    """Add new entry to file"""
    f = open(LOCATION_FILE, 'a')
    lines = retrieveFileData()
    print lines
    if line not in lines:
        f.write(line + '\n')
        lines.add(line)
        f.close()
    else:
        print "entry already exists"

if __name__ == "__main__":
    while True:
        line = raw_input("Enter line manually: ")
        add_line(line)
        if line == 'quit':
            break
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文