读取和打印数据 - colab
Reading and print data - 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])
请协助我尝试打印结果,但当我 运行 代码时没有打印任何内容。
#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])