社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Weylin Piegorsch  »  全部回复
回复总数  1
4 年前
回复了 Weylin Piegorsch 创建的主题 » 如何从python脚本运行终端命令,并将输出保存到。csv文件?[重复]

如果您的CSV文件有列标题,则此选项有效。

[ user@system currentDir ]$ ./ProgramThatCreatesCSVData
first,second,third,fourth
1,2,3,4
9,10,11,12
a,b,c,d
5,6,7,8
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$ cat CSVtoDict.py
#!/usr/bin/python3
"""Sample program to open a pipe to run a command.
That command generates a CSV with heading names in the first row.
Output of this program is a conversion of that CSV to a list of dictionaries,
in pprint format."""

import csv, pprint, subprocess, io

pipe = subprocess.Popen(["./ProgramThatCreatesCSVData"], stdout=subprocess.PIPE)
pipeWrapper = io.TextIOWrapper(pipe.stdout)
pipeReader = csv.DictReader(pipeWrapper)
listOfDicts = [ dict(row) for row in pipeReader ]

pprint.pprint(listOfDicts)

[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$
[ user@system currentDir ]$ python3 CSVtoDict.py
[{'first': '1', 'fourth': '4', 'second': '2', 'third': '3'},
 {'first': '9', 'fourth': '12', 'second': '10', 'third': '11'},
 {'first': 'a', 'fourth': 'd', 'second': 'b', 'third': 'c'},
 {'first': '5', 'fourth': '8', 'second': '6', 'third': '7'}]
[ user@system currentDir ]$