python - 读取和打印数据 - colab
问题描述
请协助我尝试打印结果,当我运行代码时没有打印任何内容。
#read the tweets stored in the file
tweets_data_path='tweet.txt'
tweets_data=[]
tweets_file=open(tweets_data_path,"r")
#read in tweets and store on list
for line in tweets_file:
tweet=json.loads(line)
tweets_data.append(tweet)
tweets_file.close()
print(tweets_data[0])
我试图更改最后一行的缩进,但收到以下错误
#read the tweets stored in the file
tweets_data_path='tweet.txt'
tweets_data=[]
tweets_file=open(tweets_data_path,"r")
#read in tweets and store on list
for line in tweets_file:
tweet=json.loads(line)
tweets_data.append(tweet)
tweets_file.close()
print(tweets_data[0])
IndexError Traceback (most recent call last)
<ipython-input-48-f5407f1436ea> in <module>()
8 tweets_data.append(tweet)
9 tweets_file.close()
---> 10 print(tweets_data[0])
IndexError: list index out of range
请指教
解决方案
如果文件为空,则没有可打印的内容。这是我的建议,以避免由于空文件导致的异常:
# read the tweets stored in the file
tweets_data_path = 'tweet.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
# read in tweets and store on list
for line in tweets_file:
tweet = json.loads(line)
tweets_data.append(tweet)
tweets_file.close()
if len(tweets_data) > 0:
print(tweets_data[0])
推荐阅读
- regex - 允许在 url 中使用破折号的正则表达式
- c# - C# - NEST 库中的 BulkDescriptor() 方法覆盖数据
- react-admin - 如何在 react-admin 的列表视图中自定义过滤表单 onChange 行为
- asp.net - 我想从下拉列表中选择特定名称并将该名称传递给控制器。我该怎么做?
- reactjs - 我应该在三元运算符里面申请什么父?
- unity3d - Unet 不同步客户端-服务器、服务器-客户端之间的浮点值
- vba - 检查前端和后端 Access 数据库之间的有效连接
- c# - 在 Azure 函数 V2 上注册 3rd 方 DI 框架(Lamar/Autofac)的正确方法
- java - Stripe 通过 API 接受付款
- javascript - 如何编写 router.navigate 方法以从 angular6 中的子模块导航到父模块