python - 使用 DictReader 从 csv 读取特定列

标签 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'])

但我一直明白

File ....\Python36\lib\csv.py", line 87, in init self.reader = reader(f, dialect, *args, **kwds) TypeError: argument 1 must be an iterator

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

最佳答案

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

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

关于python - 使用 DictReader 从 csv 读取特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50910915/

相关文章:

python - 使用Python将XML解析为CSV nonetype错误

mysql - 在 mysql 中收到 "data truncated for column"警告

java - 在 Java 中将文本文件转换为二维数组

python - Fabric 说 'no route to host' ,尽管我可以通过 SSH 访问它

python - 如何在事件回调之间保持 python 生成器的状态

python - 如何检查 BigQuery 查询结果何时返回零记录?

python - 如何从张量中提取子矩阵?

python - 根据 csv 文件移动文件

python - 无法从 App Engine 中的 FTP 服务器下载 csv 文件

csv - 从 Amazon Redshift UNLOAD 创建 RFC-4180 友好的 CSV 文件的最佳方法是什么?