bash - 将目录中所有文件的名称及其绝对路径写入 bash 中的 csv 文件
问题描述
这比我预期的要难,但我有一个文件夹,里面有大约 100 个 .csv 格式的数据集。
我想创建一个包含以下字段的 .csv 文件:
- 第一个字段是文件名。例如
user_profile.csv
- 第二个字段是文件的绝对路径,例如
/Users/yuqli/project/user_profile.csv
我想用 bash 命令来做到这一点。但到目前为止,我只能做:
ls >> out.csv
它将所有文件名写入一个 txt 文件...我看到有些人使用 for 循环,但在 .csv 文件中操作行似乎令人生畏,我不知道在 for 循环中放什么...
我最好只使用 Python 吗?任何帮助表示赞赏...谢谢!
解决方案
感谢上述大师的建议,我想出了这个 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')
推荐阅读
- jasmine - Protractor - 套件日志在 Jasmine 记者中被分成多个套件
- oauth-2.0 - OAuth 2 Java 休息 API
- scala - Scala映射显式类型
- javascript - AngularJS ng-repeat 没有从 crontoller 获取数据
- hyperledger-fabric - 在不同的机器中连接 2 个现有的组织 - Hyperledger Fabric
- android - Livedata 观察者的多个实例
- asp.net - 使用 vb.net 在浏览器中弹出窗口
- regex - regexp_replace() - 匹配但不在行尾替换
- reactjs - 向父 DOM 元素添加/删除类 React js
- tfs - 如何将过去迭代的排序顺序更改为 TFS 积压/董事会中的降序?