使用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) ...更多推荐
发布评论