简体   繁体   English

如何在不使用熊猫的情况下将 append 列从 csv 文件到另一个 csv 文件?

[英]how to append a column from a csv file to another csv file without using panda?

I want to append a column from 'b.csv' file and put it into 'a.csv' file but it only add a letter and not the whole string.我想 append 来自“b.csv”文件的列并将其放入“a.csv”文件,但它只添加一个字母而不是整个字符串。 I tried searching in google but there's no answer.我尝试在谷歌搜索,但没有答案。 I want to put the column under the headline "number".我想将该列放在标题“数字”下。 This is my code:这是我的代码:

f = open('b.csv')
default_text = f.read()
with open('a.csv', 'r') as read_obj, \
        open('output_1.csv', 'w', newline='') as write_obj:
    csv_reader = reader(read_obj)
    csv_writer = writer(write_obj)
    for row in csv_reader:
        row.append(default_text[8])
        csv_writer.writerow(row)

This is the info in 'a.csv'这是“a.csv”中的信息

name,age,course,school,number
Leo,18,BSIT,STI
Rommel,23,BSIT,STI
Gaby,33,BSIT,STI
Ranel,31,BSIT,STI

This is the info in 'b.csv'这是“b.csv”中的信息

1212121
1094534
1345684
1093245

You can just concat rows read from both CSV file and pass it immediately to writer:您可以连接从两个 CSV 文件中读取的行并立即将其传递给 writer:

import csv
from operator import concat

with open(r'a.csv') as f1, \
        open(r'b.csv') as f2, \
        open(r'output_1.csv', 'w', newline='') as out:
    f1_reader = csv.reader(f1)
    f2_reader = csv.reader(f2)
    writer = csv.writer(out)
    writer.writerow(next(f1_reader))  # write column names
    writer.writerows(map(concat, f1_reader, f2_reader))

So we initialize csv.reader() for both CSV files and csv.writer() for output.所以我们初始化csv.reader()为 CSV 文件和csv.writer()为 Z78E6221F6393D14CEDFZFZ666。 As first file ( a.csv ) contains column names, we read it using next() and pass to .writerow() to write them into output without any modifications.由于第一个文件a.csv包含列名,我们使用next()读取它并传递给.writerow()以将它们写入 output 而不进行任何修改。 Then using map() we can iterate over both readers simultaneously applyingoperator.concat() which concatenate rows returned from both reader.然后使用map()我们可以遍历两个阅读器,同时应用operator.concat()连接从两个阅读器返回的行。 We can pass it directly to .writerows() and let it consume generator returned by map() .我们可以将它直接传递给.writerows()并让它使用map()返回的生成器。


You can help my country, check my profile info .你可以帮助我的国家,查看我的个人资料信息

If only pandas cannot be used, then it's convenient to use Table helper from convtools library ( github ).如果只有 pandas 不能使用,那么使用convtools库中的Table helper ( github ) 会很方便。

from convtools.contrib.tables import Table
from convtools import conversion as c

(
    Table.from_csv("tmp/1.csv", header=True)
    # this step wouldn't be needed if your first file wouldn't have missing
    # "number" column
    .drop("number")
    .zip(Table.from_csv("tmp/2.csv", header=["number"]))
    .into_csv("tmp/results.csv")
)

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

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