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)
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.
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.
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}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With