首页 > 解决方案 > 将目录中所有文件的名称及其绝对路径写入 bash 中的 csv 文件

问题描述

这比我预期的要难,但我有一个文件夹,里面有大约 100 个 .csv 格式的数据集。

我想创建一个包含以下字段的 .csv 文件:

我想用 bash 命令来做到这一点。但到目前为止,我只能做:

ls >> out.csv

它将所有文件名写入一个 txt 文件...我看到有些人使用 for 循环,但在 .csv 文件中操作行似乎令人生畏,我不知道在 for 循环中放什么...

我最好只使用 Python 吗?任何帮助表示赞赏...谢谢!

标签: bashcsv

解决方案


感谢上述大师的建议,我想出了这个 Python 程序,它 1)提取文件名和 2)提取每个文件中的字段名。欢迎任何意见。谢谢!

import os
import csv
info = {}    # store all information into a Python dictionary
for filename in os.listdir(os.getcwd()):
    with open(filename, newline='') as f:
        reader = csv.reader(f)
        row1 = next(reader)
        info[filename] = row1

path = os.getcwd()
header = 'field, dataset, path'
write_file = "output.csv"
with open(write_file, "w") as output:
    output.write(header + '\n')
    for key, value in info.items():
        for elem in value:
            curr_path = path + key
            line = '{0}, {1}, {2}'.format(elem, key, curr_path)
            output.write(line + '\n')

推荐阅读