【问题标题】:Importing CSV Data As Variable-Value Pairs in Python在 Python 中将 CSV 数据作为变量值对导入
【发布时间】:2016-10-24 00:56:15
【问题描述】:

我正在尝试在 Python 中模拟 bash 概念,以将 CSV 中的数据作为变量值对。我有一个 CSV 文件,无论如何都可以制作(由我决定)。目前看起来是这样的……

Unit,pixels
AvgVol,87654
AvgLen,5432

以及类似的一长串值。如果修改 CSV 可以使其工作,请也建议这样做。

我正在尝试以这样一种方式阅读这些内容,以便我可以使用 Unit87654 使用 访问像 pixels 这样的值>AvgVol 无需记住它们的索引,类似于 catsource 在 bash 中的操作。无论如何,这很有用,因此我可以使用变量列表及其值来编辑我的 CSV 文件,而不必担心它们的顺序或在引用特定变量的值时发生任何事情。稍后我会将它们用于其他计算,这样我就可以像

if AvgVol>MaxVol:
   print 'something'

感谢任何帮助,我希望它可以在没有太多复杂性的情况下实现。谢谢!!

【问题讨论】:

标签: python bash csv


【解决方案1】:

您可以使用csv 模块来执行您的任务。

这是一个例子:

$ cat csvfile 
Unit,pixels
AvgVol,87654
AvgLen,5432
$ python3 script.py 
{'Unit': 'pixels', 'AvgLen': 5432, 'AvgVol': 87654}

这里是python程序:

import csv

csvdict={}
with open('csvfile', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        csvdict[row[0]]=(int(row[1]) if row[1].isdigit() else row[1])

print(csvdict)

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 2019-03-10
    • 2018-02-25
    • 2018-12-01
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多