Python 使用DictReader从csv读取特定列
从csv文件中获取第二列值时遇到问题 以下代码将数据写入csv文件Python 使用DictReader从csv读取特定列,python,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 +
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,方言,*args,**kwds)类型错误:参数1必须是迭代器
你知道这里可能出了什么问题吗?我想你需要把
文件改成csvfile
with open(file, 'r', encoding="utf8") as csvfile:
reader = csv.DictReader(csvfile)
...
如果要将路径
对象传递给csv.DictReader,则应传递一个打开的(用于读取)文件
对象。