如何使用 Python 将数据附加到 CSV 文件的一行并移动它?

How to append data to a line of a CSV file and move it using Python?

提问人:InsertName 提问时间:8/30/2023 最后编辑:marc_sInsertName 更新时间:9/1/2023 访问量:56

问:

我需要能够将额外的项目添加到由基于用户输入的搜索算法指示的 CSV 文件的预先存在的行中(搜索代码已经到位),并将现在包含添加项目的行移动到不同的 CSV 文件中,同时将其从旧文件中删除

搜索代码:

found = False
while found == False:
  reg = input("\nEnter the registration number of the car sold\n")
  with open("Cars.csv") as sale:
    file = csv.reader(sale)
    for i in file:
      if i[2] == reg:
        found = True 
  if found != True:
    print("\nRegistration not found, please try again\n")
sale.close()

写入 Cars.CSV 的代码:

if Choice1==1 and role==1:#buy a car
  confirm="n"
  while confirm!="y":
    fileopen = open("Cars.csv","a", newline="")
    file = csv.writer(fileopen)
    buyer=input("\nWhat is your name?\n")
    brand=input("\nWhat brand made the car?\n")
    colour=input("\nWhat colour is the car?\n")
    reg=input("\nWhat is the car's registration number?\n")
    broughtfor=input("\nHow much did the car cost?\n")
    date=input("\nWhat date was the car brought on?\n")
    data=[brand,colour,reg,broughtfor,date,buyer]
    #data inputed and compiled into a list
    confirm=input("Are you sure this information is correct\ny/n\n")#confirmation prompt
    if confirm=="y":
      file.writerow(data)#writing to file if confirmed
    if confirm != "y":
      Choice2=int(input("\nWould you like to:\n 1) Re-enter the information\n 2) Exit to the menue\n")) #allows reentry of data or a return to the menue
      if Choice2==2:
        confirm="y" #cancels the input
  fileopen.close()
  print("Thank you\n")

要求添加输入的代码:

name=input("\nPlease enter your name\n")
price=int(input("\nHow much did this car sell for?\n"))
date=input("\nWhat date was the car sold?\n")
data=[price, date, name]

我得到的测试数据表的图像,中间的 3 列是需要添加到其余列中的列,最后 2 列是在需要时计算的

一行写着品牌:宝马,颜色:银色,注册号:ABC123,购买价格:20000,购买日期:10 4 23,买家:亚当,销售价格:30000,销售日期:20 4 23,卖家:Daisy,买家 com:200,卖家 com:300

我还没有测试任何代码,因为我对如何处理这个问题没有任何想法

python csv 文件

评论

0赞 Michael Butscher 8/30/2023
您不能在文件中间删除或插入字节。你必须重写它(至少从更改点到最后)。
0赞 Codist 8/30/2023
显示 Cars.csv 文件的示例,以阐明您要执行的操作

答:

0赞 Codist 8/30/2023 #1

以下是从原始文件中删除条目的方法。您对需要放入其他文件的内容的描述令人困惑。

import csv

# open the file. note that we use 'r+' mode because we may rewrite it
with open(file='Cars.csv', mode='r+', newline='') as csvdata:
    # make an in-memory list of the csv data
    data = list(csv.reader(csvdata))
    reg = input('Enter registration number: ')
    # search the list
    for i, row in enumerate(data[1:], 1):
        # try to match the registration number
        if row[2] == reg:
            # remove entry from list
            data.pop(i)
            # go to BOF
            csvdata.seek(0)
            # rewrite the rows
            csv.writer(csvdata).writerows(data)
            # don't forget to truncate
            csvdata.truncate()
            break
    else:
        print('Not found')