python - 检查一个字符串是否在一个文件中,如果它没有附加它
问题描述
所以我试图让程序检查一个字符串是否在文件中,如果它不只是将它附加到末尾(在一个新行中),如果不是,它什么也不做。
我已经尝试过 w+ 但它只是覆盖整个文件而不是附加它,如果我尝试 a+ 它只是附加而不检查,即使字符串在文件中。所以我的问题是:
如何设法检查字符串是否已经在文件中,如果没有,请附加它。
这是一个示例代码:
with open("testfile.txt", "a+") as testfile:
word = "test"
inhalt = testfile.read ()
if word not in inhalt:
testfile.write ("something"+ "\n")
else:
pass
解决方案
我更喜欢这样的任务分两步完成。见下文:
with open("testfile.txt") as testfile:
word = "test"
inhalt = testfile.read ()
if word not in inhalt:
with open("testfile.txt", 'a') as testfile:
testfile.write(word+ "\n")
推荐阅读
- matlab - 带有键盘功能的Matlab声音
- java - Java程序:程序中异常类的问题,以按顺序对数组进行排序
- c# - OpenXml SDK PowerPoint 朝阳图
- sql - 从其他数据库中按计数 id 获取排序项目
- ruby-on-rails - 在 Mac OS X 10.15 Catalina 上安装 Ruby On Rails 时出错
- sql - 在 sql 中分组结果
- go - 如何在没有任何存储的情况下生成 oidc 状态?
- javascript - 在 React 公共文件夹中存储数据
- python - pip3没有setuplib就不能安装setupdocx,但是没有setupdocx就不能安装setuplib?
- reactjs - 带有 React Hooks 的多模态