Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in file

I am trying to read the following file line by line and check if a value exists in the file. What I am trying currently is not working. What am I doing wrong?

If the value exists I do nothing. If it does not then I write it to the file.

file.txt:

123
345
234
556
654
654

Code:

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)
like image 902
user3702643 Avatar asked Jul 05 '20 12:07

user3702643


People also ask

How do you check if a string is present in a file in Linux?

Syntax. grep -q [PATTERN] [FILE] && echo $? The exit status is 0 (true) if the pattern was found; The exit status is 1 (false) if the pattern was not found.


2 Answers

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

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.

like image 71
chn Avatar answered Sep 19 '22 14:09

chn


I would consider several changes.

1: Use with to automatically close the file.
2: Use strip() to remove leading or trailing stuff, like \n
3: Use a break for the loop.
4: Add \n in the write part.

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}")
like image 21
Saelyth Avatar answered Sep 19 '22 14:09

Saelyth