首页 > 解决方案 > 如何在while循环之前一劳永逸地提示用户输入?

问题描述

我正在编写一个 Python 脚本,该脚本从名为“read_file”的 pandas DataFrame 中获取特定数据并将其写入 csv 文件。为此,我循环遍历 DataFrame 的行,直到满足某个条件,即当我将数据放入字典中时,我使用“to_csv”函数更新 csv 文件。执行相同操作的方法肯定更少 - 更简单 - 但我将优化改天(尽管我愿意接受建议)。

我想知道是否有办法提示用户决定他们想要写入数据的方式。基本上,我是在问他们是否愿意:

  1. 覆盖文件,然后通过to_csv函数的附加模式逐行更新(每次我们通过循环)
  2. 每次运行脚本时不要覆盖文件,只需将数据附加到它(这意味着运行后它会变大)。

到目前为止,我的代码如下所示:

i = 0
for index, row in read_file.iterrows():
case = row['Case']
first = case.split('-')[0]
second = case.split('-')[1]
third = case.split('-')[2]
fourth = case.split('-')[3]
fifth = case.split('-')[4]
if first == 'X01': # if1
    if second == '01': # if2
        if fourth == '04': # if3
            i += 1
            Ax = float(row['Ax'])
            Ay = float(row['Ay'])
            Az = float(row['Az'])
            ENT = float(row['ENT'])
            Ips = (Ax**2 + Ay**2 + Az**2)**(0.5)
            beta = float(row['beta'])
            date = row['Date'].replace("/", "-")
            totalP = float(row['Total.P'])

            data = pd.DataFrame({'Case': [str(case)],
                'ENT': [ENT],
                'total P': [totalP]},
                index = [i])

            filename = 'curve_{}-{}-{}-{}_I{}-B{}-D{}.csv'.format(first,second,third,fourth,round(Ips, 2),beta,date)
            if os.path.getsize(filename):
                print('Curve file not empty.')
                while True:
                    inp = input('Do you want to: A) Append the file. B) Overwrite the file. [A/B]? : ')
                    if inp in ['A', 'B']:
                        break
                if inp == 'A':
                    print('Appending... ')
                    data.to_csv(filename, mode='a')
                elif inp == 'B':
                    print('Overwriting... ')
                    data.to_csv(filename, mode='w')

但是,每次满足条件 if1、if2 和 if3时都会出现此提示,这很常见。有没有办法一劳永逸地指定输入?

谢谢


编辑:

示例文件将是:

案子 日期 耳鼻喉科 测试版 斧头 阿兹 总磷
X01-01-ARK-03-001 21 年 9 月 4 日 0 0,193648827 0 15 10 3354
X01-01-ARK-03-002 21 年 9 月 4 日 3 0,000183247 0 19 12 813
X01-01-ARK-03-003 21 年 9 月 4 日 6 0,491674971 0 14 0 4111
X01-01-ARK-03-004 21 年 9 月 4 日 9 0,757163602 0 1 5 2829
X01-01-ARK-03-005 21 年 9 月 4 日 12 0,622608381 0 44 11 143
X01-01-ARK-03-006 21 年 9 月 4 日 14 0,543299744 0 34 3 4732
X01-01-ARK-03-007 21 年 9 月 4 日 15 0,624404717 0 16 9 3052
X01-01-ARK-03-008 21 年 9 月 4 日 16 0,977021142 0 23 9 2178
X01-01-ARK-03-009 21 年 9 月 4 日 17 0,97697958 0 3 12 191
X01-01-ARK-04-001 21 年 9 月 4 日 0 0,440339098 0 33 9 1472
X01-01-ARK-04-002 21 年 9 月 4 日 3 0,982879346 0 49 2 253
X01-01-ARK-04-003 21 年 9 月 4 日 6 0,740821012 0 27 5 4100
X01-01-ARK-04-004 21 年 9 月 4 日 9 0,48267087 0 38 0 3582
X01-01-ARK-04-005 21 年 9 月 4 日 12 0,578068153 0 45 11 3320
X01-01-ARK-04-006 21 年 9 月 4 日 14 0,541974323 0 41 0 2064
X01-01-ARK-04-007 21 年 9 月 4 日 15 0,445777405 0 22 6 435
X01-01-ARK-04-008 21 年 9 月 4 日 16 0,263795323 0 27 10 1251
X01-01-ARK-04-009 21 年 9 月 4 日 17 0,708550336 0 44 12 60

预期的输出是:

指数 案子 耳鼻喉科 总磷
1 X01-01-ARK-04-001 0 1472
2 X01-01-ARK-04-002 3 253
3 X01-01-ARK-04-003 6 4100
4 X01-01-ARK-04-004 9 3582
5 X01-01-ARK-04-005 12 3320
6 X01-01-ARK-04-006 14 2064
7 X01-01-ARK-04-007 15 435
8 X01-01-ARK-04-008 16 1251
9 X01-01-ARK-04-009 17 60

标签: pythonpandasdataframecsvappend

解决方案


在遍历文件之前询问用户问题,这样问题只会被询问(并回答)一次:

while True:
    inp = input('Do you want to: A) Append the file. B) Overwrite the file. [A/B]? : ')
    if inp in ['A', 'B']:
        break

i = 0
for index, row in read_file.iterrows():
case = row['Case']
first = case.split('-')[0]
second = case.split('-')[1]
third = case.split('-')[2]
fourth = case.split('-')[3]
fifth = case.split('-')[4]
if first == 'X01': # if1
    if second == '01': # if2
        if fourth == '04': # if3
            i += 1
            Ax = float(row['Ax'])
            Ay = float(row['Ay'])
            Az = float(row['Az'])
            ENT = float(row['ENT'])
            Ips = (Ax**2 + Ay**2 + Az**2)**(0.5)
            beta = float(row['beta'])
            date = row['Date'].replace("/", "-")
            totalP = float(row['Total.P'])

            data = pd.DataFrame({'Case': [str(case)],
                'ENT': [ENT],
                'total P': [totalP]},
                index = [i])

            filename = 'curve_{}-{}-{}-{}_I{}-B{}-D{}.csv'.format(first,second,third,fourth,round(Ips, 2),beta,date)
            if os.path.getsize(filename):
                print('Curve file not empty.')
                if inp == 'A':
                    print('Appending... ')
                    data.to_csv(filename, mode='a')
                elif inp == 'B':
                    print('Overwriting... ')
                    data.to_csv(filename, mode='w')

推荐阅读