简体   繁体   English

获取 Python 代码的帮助,该代码从一个 CSV 文件中获取数据并将其插入到另一个 CSV 文件中

[英]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.我正在进行数据迁移。旧应用程序数据导出为一个 CSV 文件。 We cannot import this CSV file directly to new application.我们无法将此 CSV 文件直接导入新应用程序。 Need to create new CSV template that match with new application and import some data into this new CSV template.需要创建与新应用程序匹配的新 CSV 模板,并将一些数据导入这个新的 CSV 模板。 I would like to request code that facilitate this requirement.我想请求满足此要求的代码。

I'm not exactly sure what template you want to go to.我不确定你想要 go 到什么模板。 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如果你安装了 pandas 这更简单

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 )如果您要走 pandas 路线,请务必查看文档( read_csvto_csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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