簡體   English   中英

如何將 CSV 數據存儲到變量中?

[英]How to store CSV data into variables?

我正在嘗試將 CSV 文件中的數據存儲在 python 變量中:

我有這個 CSV:

CountryName,  ChargeMinutes
Cape Verde ,    0.00
Algeria ,       10.80
St. Lucia ,     0.00
Cameroon ,      48.75
United States , 457,929.00

我需要為每個國家/地區創建一個變量並為其分配相同的名稱並添加實際收費分鍾,例如:

cape_verde = 0
algeria = 10
st_lucia = 0
cameroon = 48 
etc...

我已經有來自 CSV 的 output,但我不知道如何將數據 output 存儲在變量中。

import csv

with open("datatmx_headers.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        country = row['CountryName']
        minutes = row['ChargeMinutes']
        print(country, minutes)

我建議您創建一個字典並將其用作變量列表。 這樣,您可以在一個地方存儲和跟蹤所有變量信息。

var = {}
with open("datatmx_headers.csv", "r") as f_input:
    csv_input = csv.DictReader(f_input)

    for row in csv_input:
        var[row['CountryName']] = row['ChargeMinutes']

在此處輸入圖像描述

我希望這會有所幫助。

因此,在達到提議的目標之前,您需要做一些事情。 由於您有“佛得角”、“聖盧西亞”、“阿爾及利亞”等特殊情況。

要處理字符串末尾有空格的“Cape Verde”和“Algeria”,您應該添加:

for row in csv_input:
    country = row['CountryName'.strip()]
    minutes = row['ChargeMinutes']
    print(country, minutes)

現在您將找不到末尾帶有空格的國家/地區名稱。 然后我們應該處理包含“。”的名稱。

for row in csv_input:
    country = row['CountryName'.strip().replace(".","")]
    minutes = row['ChargeMinutes']
    print(country, minutes)

最后,我們應該刪除兩個單詞名稱之間的空格,例如“Cape Verde”,並將其替換為“_”。

for row in csv_input:
    country = row['CountryName'.strip().replace(".","").replace(" ","_")]
    minutes = row['ChargeMinutes']
    print(country, minutes)

而不是為每個國家/地區設置一個變量,我建議您將它們全部添加到字典中,以將它們放在一個變量中並輕松訪問數據。

my_dict = {}
for row in csv_input:
    country = row['CountryName'.strip().replace(".","").replace(" ","_")]
    minutes = row['ChargeMinutes']
    my_dict[country] = minutes

在此之后,您應該能夠訪問如下數據:

print(my_dict.algeria) #prints 10.80
print(my_dict.Cape_Verde) #prints 0.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM