【问题标题】:When editing data in a CSV how do you exclude/only include certain columns?在 CSV 中编辑数据时,如何排除/仅包含某些列?
【发布时间】:2022-11-18 08:20:58
【问题描述】:

我在 Python 3 中获得了一个银行项目的客户详细信息的 CSV。我设法创建了一个函数,您可以在其中编辑客户详细信息,但我想排除最后两列,因为我无法弄清楚如何。

CSV 数据示例:

first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
Jens,Eldrid,Honorable,Male,13/11/2021,Research Associate,967.64,79.15

编辑功能:

if choice == "4":
    editClient = int(input("Please enter the index number of the client you wish to edit: "))
    print("Please enter the details for each of the following: ")
    for i in range(len(existing_clients[0])):
        newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ": ")
        existing_clients[editClient][i] = newDetails
    changes = input("Are you sure you'd like to make these changes? Enter Yes or No")
    if changes == ("Yes"):
        # Newline fixed the spacing issue I was having
        with open("mock_data.csv",   "w+", newline="") as file:
            reader = csv.writer(file)
            for i in range(len(existing_clients)):
                reader.writerow(existing_clients[i])
    if changes == ("No"):
        exit()

我试过改变

for i in range(len(existing_clients[0])):

for i in range(len(existing_clients[0:6])):

我认为这很有效,直到我在第 6 行之后尝试编辑客户端。

我也搞砸了很多

newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ": ")

无济于事。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    使用切片编辑行并排除最后两列:

    with open("mock_data.csv", "w", newline="") as file:
        writer = csv.writer(file)
        for client in existing_clients:
            writer.writerow(client[:-2]) # exclude last two columns
    

    【讨论】:

      猜你喜欢
      • 2013-02-19
      • 1970-01-01
      • 2022-09-30
      • 2011-05-09
      • 2011-02-21
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多