繁体   English   中英

使用DictReader从csv中读取特定列

[英]Read specific column from a csv with DictReader

我从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必须是迭代器

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM