我有一个包含以下字符串的文本文件(“Memory.txt”):
111111111
11111111
111111
1111111111
11111111111
111111111111111
1111111111111
我是 python 的新手,在这里也是新手,但我想知道是否有一种方法可以将另一个字符串(例如“111111111111”)添加到同一个文件(仅当文件中不存在该字符串时)。
我的代码由两部分组成:
- 读取文本文件(例如'Memory.txt')并选择文件中的字符串之一
将一个新字符串写入同一个文件(如果文件中不存在该字符串)但我无法实现这一点,下面是我在这部分的代码:
with open("Memory.txt", "a+") as myfile: for lines in myfile.read().split(): if 'target_string' == lines: continue else: lines.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")也可以写成
# Python 3
print(line, file=myfile)
# Python 2
print >>myfile, line
