检查文件中是否存在值

use*_*643 9 python python-3.7

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

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

文件.txt:

123
345
234
556
654
654
Run Code Online (Sandbox Code Playgroud)

代码:

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)
Run Code Online (Sandbox Code Playgroud)

Cih*_*han 10

There are two problems here:

  • .readlines() returns lines with \n not trimmed, so your check will not work properly.
  • a+ mode opens a file with position set to the end of the file. So your readlines() currently returns an empty list!

Here is a direct fixed version of your code, also adding context manager to auto-close the file

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
Run Code Online (Sandbox Code Playgroud)

However, I agree with @RoadRunner that better is to just use r+ mode; then you don't need the seek(0). But the cleanest is just to split out your read and write phases completely, so you don't run into file position problems.


Sae*_*yth 5

我会考虑几个变化。

1:with用于自动关闭文件。
2:strip()用于删除前导或尾随的内容,例如\n
3:使用 a breakfor 循环。
4:添加\nwrite部分。

value = "345"
with open("file.txt", "a+") as file:
    file.seek(0)
    for line in file.readlines():
        if line.strip("\n") == value:
            print('val ready exists in file')
            break
    else:
        # write to file
        file.write(f"\n{value}")
Run Code Online (Sandbox Code Playgroud)