python - 检查文件中是否存在值
问题描述
我正在尝试逐行读取以下文件并检查文件中是否存在值。我目前正在尝试的方法不起作用。我究竟做错了什么?
如果该值存在,我什么也不做。如果没有,那么我将其写入文件。
文件.txt:
123
345
234
556
654
654
代码:
file = open("file.txt", "a+")
lines = file.readlines()
value = '345'
if value in lines:
print('val ready exists in file')
else:
# write to file
file.write(value)
解决方案
这里有两个问题:
.readlines()
返回\n
未修剪的行,因此您的检查将无法正常工作。a+
模式打开一个位置设置为文件末尾的文件。所以你readlines()
当前返回一个空列表!
这是您的代码的直接固定版本,还添加了上下文管理器以自动关闭文件
value = '345'
with open("file.txt", "a+") as file:
file.seek(0) # set position to start of file
lines = file.read().splitlines() # now we won't have those newlines
if value in lines:
print('val ready exists in file')
else:
# write to file
file.write(value + "\n") # in append mode writes will always go to the end, so no need to seek() here
但是,我同意@RoadRunner 最好只使用r+
模式;那么你不需要seek(0)
. 但最干净的方法就是完全拆分您的读取和写入阶段,这样您就不会遇到文件位置问题。
推荐阅读
- mysql - 查找特定时间段内每个小时间隔的平均值
- reactjs - 即使在 .npmignore 中列入黑名单并在 package.json 文件中排除时,示例文件夹也始终包含在我的包的安装过程中
- r - 通过在 R 中对变量进行分组来对几列求和
- string - 如何将多个单词添加到字符串参数?
- sql - 如何将日期分组为周?
- vaadin - 前端编译中的递归 - 如何分析和调试这个?
- javascript - 在 React useEffect 中清除 setInterval 之前,表单不可点击
- rdf - rdfs:subPropertyOf 和 rdfs:domain
- c# - 在包含中过滤属性列表
- redis - 如何使用 redisson 为 RBlockingQueue 创建一个监听器?