【问题标题】:replace a string from user input in a CSV file (rewrite the file)替换 CSV 文件中用户输入的字符串(重写文件)
【发布时间】:2020-08-17 22:36:16
【问题描述】:

我正在尝试创建一个函数,让用户输入文件名、要替换的旧字符串和新字符串。 我在文件中有一个标题,它是用我项目中的另一个函数制作的。 我的问题是,当我进行检查并测试代码时,它会显示所需的结果,但是当我去检查目录中的文件时,没有任何变化,因此 func 基本上无法正常工作。

另一件事是while循环不能正常工作,我不知道为什么!运行代码你会明白的。

我最近开始编码,所以这让我很紧张。

功能:

import csv
from tempfile import NamedTemporaryFile
import shutil

def update_student_name():
    result = False
    f = input('Enter the file name with the extension .csv : ')
    temp_file = NamedTemporaryFile(mode= 'w' , delete=False)
    fields = ['Student Name', 'Student Grade']
    with open (f , 'r') as csv_file,temp_file:
        reader = csv.DictReader(csv_file, fieldnames=fields)
        writer = csv.DictWriter(temp_file, fieldnames=fields,lineterminator='\r')
        while not result:
            old_name = input('Enter the name you would like to update/correct: ').title()
            new_name = input('Enter the new name: ').title()
            for data in reader:
                if data['Student Name'] == old_name:
                    print(data)
                    data['Student Name']=data['Student Name'].replace(data['Student Name'],new_name)
                    print(data)
                    # print(f'({old_name}) has been updated to ({new_name})')
                    result = True
                elif data['Student Name'] != old_name:
                    print("This name is not in the file. Please enter a valid name")
            writer.writerow(data)      
    shutil.move(temp_file.name , f)

我正在处理的文件如下所示:

【问题讨论】:

  • while 循环到底有什么问题?你想让 while 循环做什么?
  • @arundeepchohan 我的想法是如果我们点击 else 部分(名称不在文件中)继续输入学生姓名,我想我会将我的代码包含在一个 while 循环中,然后如果名称中断它找到了
  • writer.writerow(data) 在循环完成后只发生一次,因此您必须缩进更多,因为它在循环内,并且它将每一行写回文件中
  • @yedpodtrzitko 感谢它现在工作了,但“else”也被执行了!!!

标签: python python-3.x loops csv shutil


【解决方案1】:

所以我的一个朋友发现我需要重新组织我的代码并且我错过了一些概念。显然,在处理像我的案例 elseelif 这样的文件时,不能在 while 循环中以这种方式使用。

  1. replace 在这件事上不能使用,结果不会保存在任何地方,因此不会写入文件。使用update 是更好的选择,因为文件是使用csv.Dictreader 读取的。
  2. 文件将从文件顶部开始搜索,因此elif 将被执行,如果以这种方式编写并且writrow 放置在代码末尾。

所以万一有人需要它,完整功能的固定代码是:

def update_student_name():
result = False
f = input('Enter the file name with the extension .csv : ')
temp_file = NamedTemporaryFile(mode= 'w' , delete=False)
fields = ['Student Name', 'Student Grade']
with open (f , 'r') as csv_file,temp_file:
    reader = csv.DictReader(csv_file)
    writer = csv.DictWriter(temp_file, fieldnames=fields, lineterminator='\r')
    writer.writeheader()
    while True:
        old_name = input('Enter the name you would like to update/correct: ').title()
        new_name = input('Enter the new name: ').title()
        for data in reader:
            if data['Student Name'] == old_name:
                data.update({'Student Name':new_name})
                print(f'({old_name}) has been updated to ({data["Student Name"]})')
                result = True
            writer.writerow(data)
        if not result:
            print("This name is not in the file. Please enter a valid name")
        else:
            break
shutil.move(temp_file.name , f)

【讨论】:

    猜你喜欢
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2018-04-27
    • 2020-05-22
    • 2019-05-19
    • 2015-07-16
    相关资源
    最近更新 更多