首页 > 解决方案 > 检查文件中是否存在值

问题描述

我正在尝试逐行读取以下文件并检查文件中是否存在值。我目前正在尝试的方法不起作用。我究竟做错了什么?

如果该值存在,我什么也不做。如果没有,那么我将其写入文件。

文件.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)

标签: pythonpython-3.7

解决方案


这里有两个问题:

  • .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). 但最干净的方法就是完全拆分您的读取和写入阶段,这样您就不会遇到文件位置问题。


推荐阅读