使用DictReader从csv中读取特定列(Read specific column from a csv with DictReader)

编程入门 行业动态 更新时间:2024-10-27 06:18:36
使用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必须是迭代器

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

I have a problem getting the 2nd column values from a csv file.

The following code writes data to the csv file

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})

and I am trying to get the emotion column from the csv the following way

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

But I keep getting that

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

Any idea what might be going wrong here?

最满意答案

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

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

i think you need to change from file to csvfile

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

更多推荐

本文发布于:2023-08-06 08:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445269.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:csv   DictReader   Read   column   specific

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!