如何防止我的列表项在写入 CSV 时被分解成单独的字符串?
how do I prevent my list items from being broken up into individual strings when writing to CSV?
当写入我的 CSV 时,我的列表项被分解成单独的字符串,即使我正在使用追加功能。我认为问题在于我如何使用 writerow,但我不太确定。
这是我的代码。
twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
input_path = 'doc_list.csv'
output_path = 'doc_tweets.csv'
docs_array = []
with open(input_path, 'r') as doc_file:
docs = csv.reader(doc_file)
for row in docs:
docs_array.append(row)
with open(output_path, 'w') as tweets_file:
writer = csv.writer(tweets_file, quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for name in docs_array:
tweet_list = []
user_timeline = twitter.get_user_timeline(screen_name=name, count=100, include_retweets=False)
for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow(li)
del tweet_list[:]
del docs_array[:]
在为 writerow 迭代之前列表中的内容的一个示例是
, '@etritabaugh gorgeous',
经过writer.writerow(li)后变成
@,e,t,r,i,t,a,b,a,u,g,h, ,g,o,r,g,e,o,u,s
writerow
期望一个 iterable,一旦它得到一个字符串,字符串中的每个字符都会 splitted 作为单独的列。
要将整个列表作为单行写入 csv,您不需要第二个 for 循环:
for tweet in user_timeline:
tweet_list.append(tweet['text'])
writer.writerow(tweet_list)
相反,如果您想将列表中的每个项目写成 单独的 行,则使用列表文字来防止将字符串用作行:
for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow([li])
# ^ ^
当写入我的 CSV 时,我的列表项被分解成单独的字符串,即使我正在使用追加功能。我认为问题在于我如何使用 writerow,但我不太确定。
这是我的代码。
twitter = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
input_path = 'doc_list.csv'
output_path = 'doc_tweets.csv'
docs_array = []
with open(input_path, 'r') as doc_file:
docs = csv.reader(doc_file)
for row in docs:
docs_array.append(row)
with open(output_path, 'w') as tweets_file:
writer = csv.writer(tweets_file, quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
for name in docs_array:
tweet_list = []
user_timeline = twitter.get_user_timeline(screen_name=name, count=100, include_retweets=False)
for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow(li)
del tweet_list[:]
del docs_array[:]
在为 writerow 迭代之前列表中的内容的一个示例是
, '@etritabaugh gorgeous',
经过writer.writerow(li)后变成
@,e,t,r,i,t,a,b,a,u,g,h, ,g,o,r,g,e,o,u,s
writerow
期望一个 iterable,一旦它得到一个字符串,字符串中的每个字符都会 splitted 作为单独的列。
要将整个列表作为单行写入 csv,您不需要第二个 for 循环:
for tweet in user_timeline:
tweet_list.append(tweet['text'])
writer.writerow(tweet_list)
相反,如果您想将列表中的每个项目写成 单独的 行,则使用列表文字来防止将字符串用作行:
for tweet in user_timeline:
tweet_list.append(tweet['text'])
for li in tweet_list:
writer.writerow([li])
# ^ ^