检查文件中是否存在值

Check if value exists in file

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

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

file.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)

您的 python 脚本适合我。我猜 else 语句的最后一行应该是 file.write(value) 而不是 file.write(val).

我会考虑一些改变。

1:使用with自动关闭文件
2:使用 strip() 删除开头或结尾的内容,例如 \n
3:对循环使用break
4:在write部分添加\n

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}")

这应该有效:)

filename = 'file.txt'
value = '345'

with open(filename) as f:
    if value in f.read(): # read if value is in file 
        print('Value is in the file')

这将检查该值是否在文件中以及是否不存在。它将为文件增加价值。

filename = 'file_1.txt'
value = '999'

with open(filename, 'r+') as f:
    if value in f.read():
        print(f"Value {value} is in the file")
    else:
        print("The value not in the file.\nTherefore, saving the value in the file.")
        f.write(f"{value}\n")

这里有两个问题:

  • .readlines() returns 行 \n 未修剪,因此您的检查将无法正常工作。
  • a+ 模式打开文件,位置设置为文件末尾。所以你的 readlines() 当前 returns 是一个空列表!

这是您代码的直接固定版本,还添加了上下文管理器以自动关闭文件

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)。但最干净的只是将您的读取和写入阶段完全分开,这样您就不会 运行 陷入文件位置问题。

在使用 io 时,推荐的方法是使用 context managerContext managers 允许您在需要时精确分配和释放资源。上下文管理器使用最广泛的示例是 with 语句。如果你有一个大文件最好不要使用 file.readlines()read() 方法。 readlines() 方法 returns a list 包含文件中的每一行作为列表项。最好逐行迭代文件流(生成器)。总是使用 try 除了 io 操作! :

values=['123','233'...]
try:
    with open("file.txt", "r+") as fp:
        for line in fp:
            for val in values:
                if val not in line.strip():
                    fp.write(val)
                else:
                    print('val ready exists in file')
except (OSError,...): #catch what ever you think this code above can raise, and re raise in except block if you want.
#do exception handling

既然要打开文件进行读写,建议使用open()中的r+模式。这将在文件的开头打开文件,因为我们要先读取所有行。使用 a+ 将在文件末尾打开文件进行读写,这将导致 linesreadlines().

给你一个空列表

在检查该值是否存在之前,您还需要从 lines 中去除换行符。这是因为 345 不等于 345/n。我们可以使用列表理解来使用 str.rstrip()lines 中去除换行符,这会从右侧去除空白。此外,如果您必须对多个值进行重复查找,可能值得将 lines 转换为 set 以进行恒定时间查找,而不是使用列表进行线性搜索。

它也值得在阅读文件时使用 With Statement Context Managers,因为文件的关闭是为您处理的。

value = '345'

with open("file.txt", mode="r+") as file:
    lines = [line.rstrip() for line in file.readlines()]

    if value in lines:
        print('value ready exists in file')
    else:
        file.write(f"{value}\n")

另一种选择是使用f.seek(0)a+来设置文件开头的位置,如答案所示。但是我认为这使事情过于复杂,而且使用 r+ 模式更容易。

当您以“a+”模式打开文件时,readlines() 方法开始读取的文件光标将位于末尾,因此 readlines 不会读取任何内容。您需要执行 f.seek(0) 才能将光标移动到开头。

file = open("file.txt", "a+")
file.seek(0)
lines = [line.strip() for line in file.readlines()]
print(lines)

value = '345'
if value in lines:
    print('val ready exists in file')
else:
    print("else")
    # write to file
    file.write(value)
file.close()

readlines() 方法 returns 一个包含 \n 和每个元素的列表,所以当检查条件时,它不会与 \n 的值进行比较,所以语句总是错误的,所以我有一个代码解决你的问题。

f_name = "file.txt"
text = "102"
def check_in_file(file_name, value):
    with open(file_name, 'r') as read_obj:
        for line in read_obj:
            if value in line:
                return True
    return False
if check_in_file(f_name, text):
    print('Yes, string found in file')
else:
    print('String not found in file')
    file = open(f_name, 'a')
    file.write("\n"+text)
    file.close()