parsing - os.walk 看不到文件夹中的文件
问题描述
我前段时间在一个涉及解析推文的项目中使用了以下代码。现在,我想提取与这些推文相关的更多特征,并在我之前解析过的相同文件上重新运行它;但是,收到意外错误。错误中提到的文件 1.json 位于目录中(以及数百个其他 json)。我究竟做错了什么?
import os
import json
import pandas as pd
import numpy as np
from collections import defaultdict
elements_keys = ['created_at', 'text', 'lang', 'geo', 'location', 'quote_count', 'reply_count', 'retweet_count', 'favorite_count', 'in_reply_to_screen_name', 'screen_name', 'description', 'verified', 'followers_count', 'friends_count', 'listed_count', 'favourites_count', 'statuses_count']
elements = defaultdict(list)
for dirs, subdirs, files in os.walk('/Users/user/Desktop/'):
for file in files:
if file.endswith('.json'):
with open(file, 'r') as input_file: # print (tweet.keys())
for line in input_file:
try:
tweet = json.loads(line)
items = [(key, tweet[key]) for key in elements_keys] # should raise error if any key is missing
for key, value in items:
elements[key].append(value)
except:
continue
df=pd.DataFrame({'created_at': pd.Index(elements['created_at']),
'text': pd.Index(elements['text']),
'lang': pd.Index(elements['lang']),
'geo': pd.Index(elements['geo']),
'location': pd.Index(elements['location']),
'quote_count': pd.Index(elements['quote_count']),
'reply_count': pd.Index(elements['reply_count']),
'retweet_count': pd.Index(elements['retweet_count']),
'favorite_count': pd.Index(elements['favorite_count']),
'in_reply_to_screen_name': pd.Index(elements['in_reply_to_screen_name']),
'screen_name': pd.Index(elements['screen_name']),
'verified': pd.Index(elements['verified']),
'followers_count': pd.Index(elements['followers_count']),
'friends_count': pd.Index(elements['friends_count']),
'listed_count': pd.Index(elements['listed_count']),
'favourites_count': pd.Index(elements['favourites_count']),
'statuses_count': pd.Index(elements['statuses_count'])})
df.to_csv('df.csv')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-21-fba7b7321509> in <module>()
11 for file in files:
12 if file.endswith('.json'):
---> 13 with open(file, 'r') as input_file: # print (tweet.keys())
14 for line in input_file:
15 try:
FileNotFoundError: [Errno 2] No such file or directory: '1.json'
解决方案
哦,我想我刚刚想通了:
for dirs, subdirs, files in os.walk('/Users/user/Desktop/*.json'):
自从我使用 Python 以来已经有一段时间了。对不起 :)
推荐阅读
- javascript - Testcafe 查找元素
- r - 动态下载按钮
- django - 如何在 Route 中添加 django rest 框架身份验证?
- javascript - Highcharts 图表的默认值
- java - 使用过滤器将java for循环转换为流
- javascript - 检查键是否不存在或是否应在过滤方法中具有特定值
- java - 如何解决“Gradle 项目同步失败”?
- amazon-web-services - AWS AppSync 仅在连接查询时返回 10 个项目
- javascript - 使用 SVG 从 JSON 文件中绘制节点和链接
- woocommerce - 支持 HTTP API 运输计算所需的 Woocommerce 运输修改