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

webghufk  于 2023-09-28  发布在  Python
关注(0)|答案(1)|浏览(113)

我需要能够添加额外的项目到一个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()

写入汽车的代码:

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]

an image of the table of test data I was given, the middle 3 columns are those that need to be added to the the rest and the last 2 are computed when needed
一行写着品牌:BMW,颜色:银,注册号:ABC123,购买价格:20000,购买日期:10 4 23,买家:Adam,销售价格:30000,销售日期:20 4 23,卖家:Daisy,买方com £:200,卖家com £:300
我还没有测试任何代码,因为我没有任何想法如何处理这个问题

sg3maiej

sg3maiej1#

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

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')

相关问题