我在从 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/