自动向目录中的所有csv文件添加新的列名和字段名 [英] Automate adding new column and field names to all csv files in directories

查看:713
本文介绍了自动向目录中的所有csv文件添加新的列名和字段名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题未与任何问题链接,也没有对该问题的任何答案

我需要帮助才能在索引(0)中添加新列和目录和子目录中所有csv文件的字段名称。
我有这样的csv文件

I need help to add new column in index (0) and field names to all csv files in directories and sub-directories. I have csv files like this

apple   chocolate    smoothies
orange  dark cocoa   ice-coffee
grapes  brownies     hot-choco
banana  oreo         ice-cream

我希望输出的csv文件是这样的

I want my output csv files to be like this

Key         A       C            S
Record_01   apple   chocolate    smoothies
Record_02   orange  dark cocoa   ice-coffee
Record_03   grapes  brownies     hot-choco
Record_04   banana  oreo         ice-cream

首先,我试图将相同的Record列写入所有csv文件在文件夹和嵌套文件夹中。

其次,我试图将相同的字段名称写入文件夹和嵌套文件夹中的所有csvfiles

尝试过此代码

key = []
for row, Record in enumerate(key):
    print('Record_{}'.format(row, Record))
    row.append(row[0])
    key.appen(row)

for roots, dirs, files in os.walk('path'):
    for csvfiles in files:
        if os.path.splitext(csvfiles)[0] == '.csv':
            with open(f'{csvfiles}', 'r') as csvinput:
                with open(f'{csvfiles}', 'w') as csvoutput:
                    writer = csv.writer(csvoutput, delimiter=',')
                    writer.writerow[key]

我基本上不知道如何添加Record_ {}自动到所有csv文件。
请帮助我。谢谢您的任何答复。

I have basically no idea how to add Record_{} by automatically to all csv files. please help me. Thank you for any answers.

推荐答案

您有几种选择:


  • 将CSV数据读取到未指定列的Pandas DataFrame中。虚拟列名称将生成。重命名这些列,然后将DataFrame重新保存为CSV。

  • 打开一个新文件,写入标题,读取原始文件,然后将其写入新文件。关闭两个文件。删除原始文件,然后将新文件重命名为旧文件名。

这篇关于自动向目录中的所有csv文件添加新的列名和字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆