更新Python时避免将同一字符串写入文本文件中

2024-04-25 21:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

111111111
11111111
111111
1111111111
11111111111
111111111111111
1111111111111

我对python还很陌生,但我想知道是否有一种方法可以将另一个字符串(例如“111111111111”)添加到同一个文件中(仅当该字符串不存在于该文件中时)。在

我的代码由两部分组成:

  1. 读取文本文件(例如'内存.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')
    

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

谢谢


Tags: 文件方法内存字符串代码txttargetstring
3条回答

您需要对file对象调用“write”:

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

你只需:

# 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")也可以写成

^{pr2}$

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

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

相关问题 更多 >