gpt4 book ai didi

python - 无法分析 txt 文件 python 的输出 - ValueError : I/O operation on closed file

转载 作者:行者123 更新时间:2023-11-30 22:46:57 26 4
gpt4 key购买 nike

我正在尝试使用 Twitter 数据学习简单的文本分析。最终,我想搜索具有特定字符串的推文,并可能分析它们的收藏计数。但现在我正在尝试对我的 txt 文件进行简单的打印和搜索。

我已经弄清楚如何下载数据并将其保存到 .txt 文件,但随后我似乎可以分析它。我在 Mac 上使用 Python 3.5.2。我正在 TextWrangler 中编写代码并让它在终端中运行。

我看过有关此问题的其他文档,但我无法理解。

这是我的代码。

import tweepy
import sys
import re
consumer_key = 'xxxx'
consumer_secret = 'xxxx'
access_token = 'xxxx'
access_token_secret = 'xxxx'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
api.statuses_lookup('realdonaldtrump', include_entities=True, trim_user=False, map_= False)
tweetslist = []
print (api.statuses_lookup)
trump_tweets = api.user_timeline('realdonaldtrump', count=100)
sys.stdout = open('trump_tweet_output.txt', 'w')
for tweet in trump_tweets:
print (tweet.text)
sys.stdout.close()

##the above code works fine, creates a .txt file with tweet text

##but when I run the below-- (or any other command to analyze the file)

f = open('trump_tweet_output.txt')
line = f.readline()
print (line)
f(close)

##I get: 'ValueError: I/O operation on closed file.'

最佳答案

问题来自这一行:

sys.stdout = open('trump_tweet_output.txt', 'w')

因为再往下关闭这个文件,最终会关闭标准输出流。

我建议您只需写入该文件,而不是重新分配 sys.stdout

with open('trump_tweet_output.txt', 'w') as f:
for tweet in trump_tweets:
f.write(tweet + '\n')

然后当您尝试读取文件时,您可以编写:

with open('trump_tweet_output.txt') as f:
print(f.readline())

关于python - 无法分析 txt 文件 python 的输出 - ValueError : I/O operation on closed file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685633/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com