简体   繁体   English

如何 append 到 csv 文件中的用户指定行?

[英]How to append to user specified line in csv file?

Context:语境:

Hello - I need to append the word "CANCELLED" to the end of the specified line in a csv file.您好 - 我需要 append 将单词“CANCELLED”添加到 csv 文件中指定行的末尾。 The user of this program is asked to input (search for) a last name.该程序的用户被要求输入(搜索)姓氏。 If the last name is found in the CSV file, the word "CANCELLED" should be added to the very end of the line containing that last name.如果在 CSV 文件中找到姓氏,则应将“CANCELLED”一词添加到包含该姓氏的行的最末尾。

Problem:问题:

With the code I currently have, the line prints correctly as it should appear in the csv file.使用我目前拥有的代码,该行可以正确打印,因为它应该出现在 csv 文件中。 However, it is not being saved to the csv file for some reason.但是,由于某种原因,它没有保存到 csv 文件中。

Code is attached - please let me know if I could be more clear.附上代码 - 如果我能更清楚,请告诉我。 thanks!谢谢!

elif menuSelect == "7":
    print("CXL MENU")
    print("---------")
    print("1. Cancel by Last Name \n")
    print("2. Cancel by Confirmation #\n")
    cancelSelect = input("Select an option: ")
    lastName = input("Enter Last Name: ")
    ResStatus = "CANCELLED"
    if cancelSelect == "1":
        #open csv file, search for lastName input
        with open ('hotelguests.csv', 'rt') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                if row[0] == lastName:
                    #Write ResStatus variable to row containing lastName input
                    with open ('hotelguests.csv', 'w') as csv_file:
                        csvwriter = csv.writer(csv_file)
                        csvwriter.writerow([ResStatus])
                        print(row)

Here's a technique I invented a while back in an effort to make re-writing CSV files relatively easy by leveraging the capabilities of the fileinput module that's in Python's standard library.这是我不久前发明一种技术,旨在通过利用 Python 标准库中的fileinput模块的功能,使重写 CSV 文件相对容易。

It works by creating a temporary file and storing everything printed into it, and then effectively replaces the original file with that when it's finished.它的工作原理是创建一个临时文件并将打印的所有内容存储在其中,然后在完成后有效地替换原始文件。 In the code below a copy of original file with the extension .sav appended to it is saved (an optional feature, see the documentation).在下面的代码中,保存了附加扩展名为.sav的原始文件的副本(可选功能,请参阅文档)。

Here's how to use it to do what you want:以下是如何使用它来做你想做的事:

import csv
import fileinput

file_name = 'hotelguests.csv'
#cancelSelect = input("Select an option: ")
cancelSelect = "1"
#lastName = input("Enter Last Name: ")
lastName = "Trump"
ResStatus = "CANCELLED"
if cancelSelect == "1":
    with fileinput.FileInput(files=file_name, inplace=True, backup='.sav') as csvfile:
        for row in csv.reader(csvfile):
            if row[0] == lastName:
                row.append(ResStatus)
            print(','.join(row))  # Print as comma-separated list of values.
    print('file updated')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM