简体   繁体   English

在Python中将新列(及其数据)添加到多个CSV文件中

[英]Adding a new column (and data to it) into multiple CSV files in Python

I'm a beginner in Python, and I've been struggling to create a code to add columns to a set of similar csv files. 我是Python的初学者,我一直在努力创建代码以将列添加到一组类似的csv文件中。

Here's what I have so far: 这是我到目前为止的内容:

import csv, os

for csvFilename in os.listdir('.'):
    if not csvFilename.endswith('.csv'):
        continue
    print('Editing file ' + csvFilname + '...')

    file = open(csvFilename)
    reader = csv.reader(file)
    writer = csv.writer(open('new_' + csvFilename, 'w'))
    headers = reader.next()
    headers.append('ColName')
    writer.write(headers)
    for row in reader:
        row.append(str(row[12]) + ' ' + str(row[13]) + " some text")
        writer.write(row)

Basically, I'd like to add a column in which I had " Row 13's text + row 14's text + more text, the same every time ". 基本上,我想添加一列,其中“ 行13的文本 + 行14的文本 + 更多文本,每次都相同 ”。

I get this error message on the writer.write(headers) line, though: AttributeError: '_csv.writer' object has no attribute 'write' 我在writer.write(headers)行上收到此错误消息,但是: AttributeError:'_csv.writer'对象没有属性'write'

What should I do? 我该怎么办?

You need read the API document, 您需要阅读API文档,

https://docs.python.org/3/library/csv.html https://docs.python.org/3/library/csv.html

The csv.writer write function used writerow not the write , please check. csv.writer写入功能使用了writerow而不是write ,请检查。

The sample to write CSV file, 编写CSV文件的示例,

import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

I have to refactor your code but this should be closest to what you would like to achieve. 我必须重构您的代码,但这应该与您想要实现的代码最接近。 You would need to do exception handling and checking if there are more than 13 elements in the row, etc. 您将需要进行异常处理并检查行中是否有超过13个元素,依此类推。

import tempfile, os, csv

for csvFilename in os.listdir('.'):
    if not csvFilename.endswith('.csv'):
        continue
    print('Editing file ' + csvFilename + '...')
    with open(csvFilename, 'r') as csvFile:
        reader = csv.reader(csvFile, delimiter=',', quotechar='"')
        with open('new_' + csvFilename, 'w') as tempfile:
            writer = csv.writer(tempfile, delimiter=',', quotechar='"')
            header = True
            for row in reader:
                if (header):
                    row.append('ColName')
                    writer.writerow(row)
                    header = False
                else:
                    row.append(str(row[12]) + ' ' + str(row[13]) + " some text")
                    writer.writerow(row)

More on python csv : https://docs.python.org/3/library/csv.html 有关python csv的更多信息: https : //docs.python.org/3/library/csv.html

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

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