繁体   English   中英

检查文件中是否存在值

[英]Check if value exists in 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)

这里有两个问题:

  • .readlines()返回未修剪\n的行,因此您的检查将无法正常工作。
  • a+模式打开文件,position 设置为文件末尾 所以你的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) 但是最干净的方法就是完全拆分读写阶段,这样就不会遇到文件 position 问题。

我会考虑几个变化。

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

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

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+将在文件末尾打开文件进行读写,这将导致lines为您提供readlines()的空列表。

在检查值是否存在之前,您还需要从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+在文件开头设置 position,如@Cihan Ceyhan 的答案所示。 但是我认为这使事情变得过于复杂,并且使用r+模式更容易。

这应该工作:)

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

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

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()

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

readlines() 方法返回一个包含 \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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM