I want to delete a specific line from the CSV file.

Asked 2 years ago, Updated 2 years ago, 310 views

I want to rewrite the information in the CSV file.
There is a csv file with car information, and if the user chooses the number (x) of the car they want to buy, the line of the car purchased from the csv file will be deleted.I pasted the contents of the csv file below.On the far left is the number that the user chooses.The prices are not written on 30 and 31, but in this case, you should only see the index number on the leftmost side, so I think it doesn't matter.

I would like to do it only with the default function instead of using Pandas.In my opinion, I wrote the code in the original csv file, hoping that I could use the write mode to copy and type all the lines from the original data except for the original data.Thank you for your cooperation.

I would like to create a program like the following

Choose between buyers and dealers.

Buyer:

Dealers:

Problems

There are no errors, but only the following lines remain in the csv file:

88 volvowagon 104.3188.8 ohcfour11423

CSV of interest

index, company, body-style, wheel-base, length, engine-type, num-of-cylinders, hosepower, average-mileage, price
0, alpha-romero, convertible, 88.6, 168.8, dohc, four, 111, 21, 13495
1, alpha-romero, convertible, 88.6, 168.8, dohc, four, 111, 21, 16500
2, alpha-romero, hatchback, 94.5, 171.2, ohcv, mix, 154, 19, 16500
3, audi, sedan, 99.8, 176.6, ohc, four, 102, 24, 13950
4, audi, sedan, 99.4, 176.6, ohc, five, 115, 18, 17450
5, audi, sedan, 99.8, 177.3, ohc, five, 110, 19, 15250
6, audi, wagon, 105.8, 192.7, ohc, five, 110, 19, 18920
9, bmw, sedan, 101.2, 176.8, ohc, four, 101, 23, 16430
10, bmw, sedan, 101.2, 176.8, ohc, four, 101, 23, 16925
11, bmw, sedan, 101.2, 176.8, ohc, six, 121, 21, 20970
13, bmw, sedan, 103.5, 189, ohc, six, 182, 16, 30760
14, bmw, sedan, 103.5, 193.8, ohc, six, 182, 16, 41315
15, bmw, sedan, 110, 197, ohc, six, 182, 15, 36880
16, chevrolet, hatchback, 88.4, 141.1, l, three, 48, 47, 5151
17, chevrolet, hatchback, 94.5, 155.9, ohc, four, 70, 38, 6295
18, chevrolet, sedan, 94.5, 158.8, ohc, four, 70, 38, 6575
19, dodge, hatchback, 93.7, 157.3, ohc, four, 68, 31, 6377
20, dodge, hatchback, 93.7, 157.3, ohc, four, 68, 31, 6229
27, Honda, wagon, 96.5, 157.1, ohc, four, 76, 30, 7295
28, Honda, sedan, 96.5, 175.4, ohc, four, 101, 24, 12945
29, Honda, sedan, 96.5, 169.1, ohc, four, 100, 25, 10345
30, isuzu, sedan, 94.3, 170.7, ohc, four, 78, 24, 6785
31, isuzu, sedan, 94.5, 155.9, ohc, four, 70, 38,
32, isuzu, sedan, 94.5, 155.9, ohc, four, 70, 38,
33, jaguar, sedan, 113, 199.6, dohc, six, 176, 15, 32250
34, jaguar, sedan, 113, 199.6, dohc, six, 176, 15, 35550
35, jaguar, sedan, 102, 191.7, ohcv, twelve, 262, 13, 36000
36, mazda, hatchback, 93.1, 159.1, ohc, four, 68, 30, 5195
37, mazda, hatchback, 93.1, 159.1, ohc, four, 68, 31, 6095
38, mazda, hatchback, 93.1, 159.1, ohc, four, 68, 31, 6795
39, mazda, hatchback, 95.3, 169, rotor, two, 101, 17, 11845
43, mazda, sedan, 104.9, 175, ohc, four, 72, 31, 18344
44, mercedes-benz, sedan, 110, 190.9, ohc, five, 123, 22, 25552
45, mercedes-benz, wagon, 110, 190.9, ohc, five, 123, 22, 28248
46, mercedes-benz, sedan, 120.9, 208.1, ohcv, eight, 184, 14, 40960
47, mercedes-benz, hardtop, 112, 199.2, ohcv, eight, 184, 14, 45400
49, mitsubishi, hatchback, 93.7, 157.3, ohc, four, 68, 37, 5389
50, mitsubishi, hatchback, 93.7, 157.3, ohc, four, 68, 31, 6189
51, mitsubishi, sedan, 96.3, 172.4, ohc, four, 88, 25, 6989
52, mitsubishi, sedan, 96.3, 172.4, ohc, four, 88, 25, 8189
53, nissan, sedan, 94.5, 165.3, ohc, four, 55, 45, 7099
54, nisan, sedan, 94.5, 165.3, ohc, four, 69, 31, 6649
55, nissan, sedan, 94.5, 165.3, ohc, four, 69, 31, 6849
56, nissan, wagon, 94.5, 170.2, ohc, four, 69, 31, 7349
57, nissan, sedan, 100.4, 184.6, ohcv, six, 152, 19, 13499
61, porsche, hardtop, 89.5, 168.9, ohcf, six, 207, 17, 34028
62, porsche, convertible, 89.5, 168.9, ohcf, six, 207, 17, 37028
63, porsche, hatchback, 98.4, 175.7, dohcv, eight, 288, 17,
66, toyota, hatchback, 95.7, 158.7, ohc, four, 62, 35, 5348
67, toyota, hatchback, 95.7, 158.7, ohc, four, 62, 31, 6338
68, toyota, hatchback, 95.7, 158.7, ohc, four, 62, 31, 6488
69, toyota, wagon, 95.7, 169.7, ohc, four, 62, 31, 6918
70, toyota, wagon, 95.7, 169.7, ohc, four, 62, 27, 7898
71, toyota, wagon, 95.7, 169.7, ohc, four, 62, 27, 8778
79, toyota, wagon, 104.5, 187.8, dohc, six, 156, 19, 15750
80, volkswagen, sedan, 97.3, 171.7, ohc, four, 52, 37, 7775
81, volkswagen, sedan, 97.3, 171.7, ohc, four, 85, 27, 7975
82, volkswagen, sedan, 97.3, 171.7, ohc, four, 52, 37, 7995
86, volkswagen, sedan, 97.3, 171.7, ohc, four, 100, 26, 9995
87, volvo, sedan, 104.3, 188.8, ohc, four, 114, 23, 12940
88, volvo, wagon, 104.3, 188.8, ohc, four, 114, 23, 13415

Current state code

import csv

options=input("Please enter 1 if you are a buyer and please enter 2 if you are a dealer")

if options=="1":

    Range=input("Input 1 if you are looking for a car that costs between $0 to $15000\n"
                  "Input 2 if you are looking for the one costs between $15000 to $30,000\n"
                  "Input 3 if you are looking for the one costs more than $30,000:")
    # open the inventory file
    info=open("Automobile_data.csv", "r")
    # line=infile.readlines()

    header=next(infile)
    pecerangeL = 0
    pricerangeH = 15000
    if Range=="2":
        pricerangeL = 15000
        pricerangeH=30000
    elif Range=="3":
        pricerangeL=30000
        pricerangeH = 10000000

    For line in file:
        line=line[:-1].split(", ")

        ifline[9]==":
            continue

        elifeval(line[9])<=pricerangeHandeval(line[9])>=pricerangeL:
            print(line)

    infile.close()


    x = input("Please enter the number of the car would like to buy or enter exit:")

    if x == "exit":
         quit()


    else:
        file=open("Automobile_data.csv", "r")
        lines=file.readlines()
        file.close()


        outfile=open("Automobile_data.csv", "w")
        size = lines.__len__()
        for i in range (size-1):
            if i=="x":
                continue
            else:
                outfile.write(lines[i])

        outfile.close()

elif options=="2":

    Index=input("Index:")
    Company= input ("Company:")
    BodyStyle=input("BodyStyle:")
    WheelBase=input("WheelBase:")
    Length = input ("Length:")
    EngineType=input("EngineType:")
    NumCyl= input ("Number of Cylinder:")
    HorsePW = input ("Horsepower:")
    AV_mil=input("AverageMileage:")
    Price=input("Price:")

    NewCar= [Index, Company, BodyStyle, WheelBase, Length, EngineType, NumCyl, HorsePW, AV_mil, Price]
    with open(r'Automobile_data.csv', 'a') asf:
        writer=csv.writer(f)
        writer.writerow (NewCar)
    f.close()

python python3 csv

2022-09-30 22:01

4 Answers

The following parts of the question program

file=open("Automobile_data.csv", "r")
    lines=file.readlines()
    file.close()

    outfile=open("Automobile_data.csv", "w")
    size = lines.__len__()
    for i in range (size-1):
        if i=="x":
            continue
        else:
            outfile.write(lines[i])


    outfile.close()

Why don't you modify the as follows?

file=open("Automobile_data.csv", "r")
    lines=file.readlines()
    file.close()

    outfile=open("Automobile_data.csv", "w")
    size = lines.__len__()
    for i in range (size-1):
        lineData=lines[i].split(", ")// Separate line i of the input file with commas
        If lineData[0] == x:// If the first item (car number) divided matches the number (x) of the car you want to buy,
            continue // Do not write that line.
        else:      
            outfile.write(lines[i])// The line does not match the number of the car you want to buy, so write it to the file.

    outfile.close()//Close the file last


2022-09-30 22:01

In addition to の processing, I also reviewed various things and did the following.
The main point of correction is that I commented on ###.

import csv

#### Load the csv file first, regardless of process, as a two-dimensional list
with open('Automobile_data.csv', 'r', newline=') ascsvfile:
    header=next(csvfile)
    fullldata = [l for link csv.reader(csvfile)]

options=input("Please enter 1 if you are a buyer and please enter 2 if you are a dealer")

if options=="1":

    Range=input("Input 1 if you are looking for a car that costs between $0 to $15000\n"
                  "Input 2 if you are looking for the one costs between $15000 to $30,000\n"
                  "Input 3 if you are looking for the one costs more than $30,000:")

    pecerangeL = 0
    pricerangeH = 15000
    if Range=="2":
        pricerangeL = 15000
        pricerangeH=30000
    elif Range=="3":
        pricerangeL=30000
        pricerangeH = 10000000

    #### Extract vehicle information in the selected price range and list its index number separately.
    selected = [l for lin fullldata if [9]!='and int(l[9])<=pricerangeHandint(l[9])>=pricerangeL]
    sellindex = [l[0] for lin selected ]

    #### display car information for the selected price range
    For lin selected:
        print(l)

    x = input("Please enter the number of the car would like to buy or enter exit:")

    if x == "exit":
        quit()

    #### Exits if the specified index number does not exist in the selected price range list
    elif x not in selindex:
        print('The car with that number does not exist is out of range.')
        quit()

    else: #### This part is 相当 Equivalent new processing
        #### Create a new list excluding car information for the specified index number
        newdata=[l for lin fullldata if[0]!=x]

        #### Export the entire new list as a csv file with a header
        with open('Automobile_data.csv', 'w', newline=') ascsvfile:
            csvfile.write(header)
            writer=csv.writer(csvfile)
            writer.writerows (newdata)

elif options=="2":

    #### Separate list of all index numbers of information in the csv file
    fullindex=[l[0]for lin fullldata]

    Index=input("Index:")

    #### Determine if the index number already exists and exit if it exists
    #### (You can rewrite the existing information, but it will be complicated, so I will not answer this question.)
    if Index in fullindex:
        print('That index already exists.')
        quit()

    Company= input ("Company:")
    BodyStyle=input("BodyStyle:")
    WheelBase=input("WheelBase:")
    Length = input ("Length:")
    EngineType=input("EngineType:")
    NumCyl= input ("Number of Cylinder:")
    HorsePW = input ("Horsepower:")
    AV_mil=input("AverageMileage:")
    Price=input("Price:")

    NewCar= [Index, Company, BodyStyle, WheelBase, Length, EngineType, NumCyl, HorsePW, AV_mil, Price]
    with open('Automobile_data.csv', 'a', newline=') asf:
        writer=csv.writer(f)
        writer.writerow (NewCar)
    #### Remove unnecessary f.close()


2022-09-30 22:01

There are a lot of redundant parts and the input value has not been checked, so I have rewritten it overall.

import sys
import re

CAR_CSV_FILE = 'Automobile_data.csv'

def user_input(prompt):
  try:
    ret=input(prompt)
  except EOFError:
    print('done', file=sys.stderr)
    sys.exit(0)
  return ret

def user_input_integer(prompt):
  try:
    n=int(user_input(prompt))
  exceptValueError as:
    print(e,file=sys.stderr)
    sys.exit(1)
  return n

def buyer():
  price_range=(0,15000), (15000,30000), (30000,float('inf'))))
  p =iter(sum(price_range,()))
  prange=user_input_integer(f'''
    Input 1 if you are looking for a car that costs between ${next(p)} to ${next(p)}
    Input2 if you are looking for the one costs between ${next(p)} to ${next(p)}
    Input3 if you are looking for the one costs more than ${next(p)}
    ? ''.replace('', '))
  if prange<1 or prange>len(price_range): quit()
  prange-=1
  with open(CAR_CSV_FILE, 'r') asf:
    car_data=f.readlines()
  for car in car_data[1:]:
    car=car.trip()
    price=car.split(',')[-1].trip()
    try:
      price=int(price)
    exceptionValueError:
      continue
    if price_range [range][0]<=price<=price_range [range][1]:
      print(car)

  no = user_input(
    'Please enter the number of the car would like to buy or enter exit:')
  if no.trip() == 'exit': quit()
  with open(CAR_CSV_FILE, 'w') as outfile:
    outfile.write(
      ''.join(car for car in car_data if not re.match(rf'^{no},',car)))

def dealer():
  prompts =(
    'Index:', 'Company:', 'Body Style:', 'Wheel Base:', 'Length:',
    'Engine Type:', 'Number of Cylinder:', 'Horsepower:',
    'Average Mileage:', 'Price:')
  new_car = [ ]
  for pin prompts:
    new_car.append(user_input(p))
  with open(CAR_CSV_FILE, 'a') as outfile:
    outfile.write(','.join(new_car))

if__name__=='__main__':
  prompt='Please enter 1 if you are a buyer and please enter 2 if you are a dealer:'
  n=user_input_integer(prompt)
  if n == 1:
    buyer()
  elifn==2:
    dealer()


2022-09-30 22:01

How to handle it (as an example)

Data input

  • Create data with one line in the CSV file as one file

Data Processing

  • Delete purchased files
      Go to the
    • or "purchased" directory.
    Go to the
  • or "purchased" directory.

When creating deliverables

  • Create a CSV file by collecting the remaining files

Notes

The following actions should be performed as atomic (one uninterrupted action):

Please refer to other answers if measures have been taken (including the agreement not to take measures).If you want to take action on the program, check python semaphore.


2022-09-30 22:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.