我想检查一个字符串是否已经存在于一个文件中,并根据这个检查做一些事情。更详细地,每天启动脚本时,都会在 csv 文件中添加一行,其中一个字段是日期。
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()
Allows.csv 文件如下所示:
28/10/2017,26.7,774.31
29/10/2017,25.62,717.29
30/10/2017,26.57,717.29
在这种情况下, today_fmt 保存 '30/10/2017' 但是当我运行脚本(使用 Python3.4)时, var0 和 var1 都是真的,我不明白我错在哪里。我也试过:
var0 = str(today_fmt) not in file.read()
因为当您使用 a+ 选项打开文件时,文件指针将位于文件末尾。
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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句