简体   繁体   中英

Get help for Python code that get data from one CSV file and insert it into another CSV file

I am doing data migration.Old application data is exported as one CSV file. We cannot import this CSV file directly to new application. Need to create new CSV template that match with new application and import some data into this new CSV template. I would like to request code that facilitate this requirement.

I'm not exactly sure what template you want to go to. I'm going to assume that you either want to change the number/order of columns or the delimiter.

The simplest thing is to read it line by line and write it:

import csv
with open("Old.csv", 'r') as readfp, open("new.csv", 'w') as writefp:
    csvReader = csv.reader(readfp)
    csvWriter = csv.writer(writefp, delimiter=',')
    for line in csvReader:
        #line is a list of strings so you can reorder it as you wish. I'll skip the third column as an example. 
        csvWriter.writerow(line[:2]+line[3:])

If you have pandas installed this is even simpler

import pandas as pd
df = pd.read_csv("Old.csv")
df.drop(labels=["name_of_bad_col1", "name_of_bad_col2"], sep=',')
df.to_csv("new.csv)

If you are going the pandas route, make sure to checkout the documentations ( read_csv , to_csv )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM