0

I am attempting to append 4 elements to the end of a row in a csv file

Original
toetag1,tire11,tire12,tire13,tire14

Desired Outcome
toetag1,tire11,tire12,tire13,tire14,wtire1,wtire2,wtire3,wtire4

I attempted to research ways to do this how ever most search results yielded results such as "how to append to a csv file in python"

Can someone direct me in the correct way to solve this problem

3
  • 2
    "I attempted to research ways to do this". Where is your code that implements (or at least tries to implement) what you've researched? Commented Jun 28, 2021 at 21:56
  • My problem isnt that I cant implement the solutions that I have found my problem is that I cant find something to try to implement, if you search how to append to an existing row in a csv file you get things like this kite.com/python/answers/how-to-append-to-a-csv-file-in-python Commented Jun 28, 2021 at 21:59
  • 1
    I would recommend reading up on basic Python file operations (open a file, move to the end of the file, write to the file). Searching on "append to a CSV file" is very specific and what you are trying to do is more generically "I want to append to a file". Commented Jun 29, 2021 at 0:11

2 Answers 2

2

I advise you to use pandas module and read_csv method.

You can use the following code for instance :

data = pandas.read_csv("your_file.csv")
row = data.iloc[0].to_numpy()
row.append(['wtire1','wtire2','wtire3','wtire4'])
Sign up to request clarification or add additional context in comments.

Comments

2

You can read the csv file to a list of lists and do the necessary manipulation before writing it back.

import csv

#read csv file
with open("original.csv") as f:
    reader = csv.reader(f)
    data = [row for row in reader]

#modify data
data[0] = data[0] + ["wtire1", "wtire2", "wtire3", "wtire4"]

#write to new file
with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(data)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.