【问题标题】:Avoid writing SAME string to a text file when updating python更新 python 时避免将 SAME 字符串写入文本文件
【发布时间】:2013-09-22 17:07:52
【问题描述】:

我有一个包含以下字符串的文本文件(“Memory.txt”):

111111111
11111111
111111
1111111111
11111111111
111111111111111
1111111111111

我对 python 很陌生,在这里也是新手,但我想知道是否有办法可以将另一个字符串(例如 '111111111111')添加到同一个文件中(仅当文件中不存在该字符串时)。

我的代码由两部分组成:

  1. 读取文本文件(例如“Memory.txt”)并选择文件中的字符串之一
  2. 将一个新字符串写入同一个文件(如果文件中不存在该字符串),但我无法做到这一点,下面是我的这部分代码:

    with open("Memory.txt", "a+") as myfile:
        for lines in myfile.read().split():
            if 'target_string' == lines:
                continue
            else:
                lines.write('target_string')
    

这不会返回/做任何事情,请有人指出正确的方向或向我解释该怎么做。

谢谢

【问题讨论】:

  • 我将'Memory.txt" 固定为"Memory.txt"。确保您的代码中不存在此类问题(建议复制并粘贴到 SO)。
  • 应该是my_file.write 而不是lines.write

标签: python string file-io


【解决方案1】:

你可以这样做:

# Open for read+write
with open("Memory.txt", "r+") as myfile:

    # A file is an iterable of lines, so this will
    # check if any of the lines in myfile equals line+"\n"
    if line+"\n" not in myfile:

        # Write it; assumes file ends in "\n" already
        myfile.write(line+"\n")

myfile.write(line+"\n")也可以写成

# Python 3
print(line, file=myfile)

# Python 2
print >>myfile, line

【讨论】:

    【解决方案2】:

    你需要在文件对象上调用“write”:

    with open("Memory.txt", "a+") as myfile:
        for lines in myfile.read().split():
            if 'target_string' == lines:
                continue
            else:
                myfile.write('target_string')
    

    【讨论】:

    • @poke elif -> else
    • @yuxuan 你可以建议你自己改,如果你点击edit链接。
    • @yuxuan 哦,公平点。已为您编辑,感谢您发现错误!
    【解决方案3】:

    如果我正确理解了你想要什么:

    with open("Memory.txt", "r+") as myfile:
        if 'target_string' not in myfile.readlines():
            myfile.write('target_string')
    
    • 打开文件
    • 阅读所有行
    • 检查目标字符串是否在行中
    • 如果没有 - 追加

    【讨论】:

    • 这不行,你想用"r+"作为.readlines工作的模式。这要求您可以将整个文件保存在内存中(并且您必须读取整个文件);不调用.readlines 可以避免这种情况,但是你有我的版本;)。
    • 你是对的。是的,我认为您将文件视为可迭代的确实在任何情况下都会更好:-/
    【解决方案4】:

    找到时我会简单地将一个布尔值设置为True,如果没有则写在最后

    with open("Memory.txt", "a+") as myfile:
        for lines in myfile.read().split():
            if 'target_string' == lines:
                fnd = True # you found it
                break
        if !fnd:
            myfile.write('target_string')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多