使用DictReader从csv中读取特定列

时间:2018-06-18 13:44:09

标签: python csv

从csv文件中获取第二列值时出现问题。

以下代码将数据写入csv文件

def save_tweet_to_csv(ticker, tweet, emotion, confidence):
    file = Path(url_path + ticker + '_tweets.csv')
    if file.is_file():
        mode = 'a'
    else: 
        mode = 'w'
    with open(url_path + ticker + '_tweets.csv', mode, newline="\n", encoding="utf-8") as csvfile:
        fieldnames = ['tweet', 'emotion', 'confidence']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        if mode == 'w':
            writer.writeheader()
        writer.writerow({'tweet': tweet, 'emotion': emotion, 'confidence': confidence})

我试图通过以下方式从csv获取情感

def plot_tweets_csv(ticker):
    file = Path(url_path + ticker + '_tweets.csv')
    emotions = []
    with open(file, 'r', encoding="utf8") as csvfile:
        reader = csv.DictReader(file)
        for row in reader :
            print(row['emotion'])

但我一直得到那个

  

文件.... \ Python36 \ lib \ csv.py“,第87行, init       self.reader = reader(f,dialect,* args,** kwds)TypeError:参数1必须是迭代器

知道这里可能出现什么问题吗?

1 个答案:

答案 0 :(得分:3)

我认为您需要从file更改为csvfile

with open(file, 'r', encoding="utf8") as csvfile:
    reader = csv.DictReader(csvfile)
    ...