Birbal
Birbal

Reputation: 353

Python string not in file read

I want to check if a string is already existent in a file and base on this check do something. In more detail every day the script is launched, is adding a line to a csv file with one of the field being the date.

import time
today_fmt = time.strftime("%d/%m/%Y")
file = open('allowance.csv','a+')

var0 = today_fmt not in file.read()
var1 = '30/10/2017' not in file.read()

Where allowance.csv file looks like:

28/10/2017,26.7,774.31
29/10/2017,25.62,717.29
30/10/2017,26.57,717.29

In this case today_fmt holds '30/10/2017' but when I run the script (using Python3.4) both var0 and var1 are true and I don't understand where I'm wrong. I have also tried:

var0 = str(today_fmt) not in file.read()

Upvotes: 0

Views: 938

Answers (1)

You're awesome
You're awesome

Reputation: 301

Because when you open file with a+ option, file pointer will be at the end of file.

import time 
today_fmt = time.strftime("%d/%m/%Y") 
file = open('allowance.csv','a+')
file.seek(0) # File pointer will be at the begining of file
var0 = today_fmt not in file.read() 
file.seek(0) # Seek again 
var1 = '30/10/2017' not in file.read()

Upvotes: 2

Related Questions