【发布时间】:2020-03-05 08:11:21
【问题描述】:
这一系列的动作在python中是怎么做的?
1) 如果文件不存在则创建一个文件并插入一个字符串
2) 如果文件存在,则搜索是否包含字符串
3) 如果字符串不存在,则挂在文件末尾
我目前正在这样做,但我错过了一步
编辑 每次我调用该函数时使用此代码似乎该文件不存在并覆盖旧文件
def func():
if not os.path.exists(path):
#always take this branch
with open(path, "w") as myfile:
myfile.write(string)
myfile.flush()
myfile.close()
else:
with open(path) as f:
if string in f.read():
print("string found")
else:
with open(path, "a") as f1:
f1.write(string)
f1.flush()
f1.close()
f.close()
【问题讨论】: