python 文件操作 如何判断写入数据前是否存在相同数据.判断输入操作是否格式正确

"""
data.txt文件如下

id  date        city     temp   wind
0   03/01/2016   BJ      8      5
1   17/01/2016   BJ      12     2
2   31/01/2016   BJ      19     2
3   14/02/2016   BJ      -3     3
4   28/02/2016   BJ      19     2
5   13/03/2016   BJ      5      3
6   27/03/2016   SH      -4     4
7   10/04/2016   SH      19     3
"""
import time
import re


def write(dataset):
    c = open(dataset, "a+")
    c.seek(0)
    for line in c.readlines()[1:]:  # 8行 到 12行 是获取数据id值
        if len(line.split()) == 0:
            continue
        j = re.split(r"\s+", line.strip())
    b = int(j[0])
    print("输入日期   格式'日/月/年' ")
    while True:
        r_q = input("日期:")
        if not r_q:
            c.close()  # 日期为空时退出
            break
        try:
            time.strptime(r_q, "%d/%m/%Y")
        except:
            print("格式不正确,请重新输入.\n格式'日/月/年' ")
            continue
        else:
            c_s = input("城市:")
            try:
                w_d = int(input("温度:"))
                f_l = int(input("风力:"))
            except:
                print("输入错误 温度和风力只能输入数字")
                continue
            b += 1
            c.seek(2)
            c.write(f"{b}   {r_q}   {c_s}   {w_d}   {f_l}\n")

c = "data.txt"
write(c)

问题:
1.如何在 -4 行 写入前判断 txt 文件 是否存在相同的数据(日期 和 城市相同),存在则停止写入 跳回 15 行 进行重新输入
2. 给 -13 行 (输入城市名), 判断输入格式是否为大写字母,输入错误则重新输入
3. 给 温度和风力添加一个限制的值 如 温度 -50到100度之间 风力 1 到 9 之间 整数类型

先按行读取,然后用in判断:

list_line = file.readlines()  #有\n
# 无\n: file.read().split('\n')
if string in list_line:
    print('数据重复!')
    continue

判断输入格式是否为大写字母:

if string != string.upper():  #小写转化为大写
    print('格式错误!')
    continue

在except后面继续写:

else:
    # 无需再次判断类型,不出错即为整数
    if -50 <= w_d <= 100 and 1 <= f_l <= 9:
        ...
    else:
        print('数据超限!')
        continue

添加限制

try:
  if w_d<-50 or w_d>100:
    raise Exception("温度数据超限")
  if f_l<1 or f_l>9:
    raise Exception("风力数据超限")
  if type(w_d)!=int:
    raise Exception("温度数据格式非法")
  if type(f_l)!=int:
    raise Exception("风力数据格式非法")
except Exception as e:
  print(e)