【发布时间】:2022-01-10 09:41:33
【问题描述】:
我正在努力完成以下任务:
traverse_dir() 函数
- read a root directory, and get the names of the sub directories.
- read the sub directories and see if 'installed-files.json' file is present.
- if the 'installed-files.json' file is present in all the directories, then open them and create a excel file out of the JSON file those are present in all the sub directories.
filter_apk() 函数
- read the excel file generated in the first function and create another excel file that will store only file names ending with '.apk'.
下面是sn-p的代码:
def traverse_dir(rootDir, file_name):
dir_names = []
for names in os.listdir(rootDir):
entry_path = os.path.join(names)
if os.path.isdir(entry_path):
dir_names.append(entry_path)
for i in dir_names:
if file_name in i:
with open(file_name) as jf:
data = json.load(jf)
df = pd.DataFrame(data)
new_df = df[df.columns.difference(['SHA256'])]
new_df.to_excel('abc.xlsx')
def filter_apk():
traverse_dir(rootDir, file_name)
old_xl = pd.read_excel('abc.xlsx')
a = old_xl[old_xl["Name"].str.contains("\.apk")]
a.to_excel('zybg.xlsx')
rootDir = '<root path where sub folders resides>'
file_name = 'installed-files.json'
filter_apk()
注意:
-
我已经在单个文件夹上单独测试了代码,它的工作方式很迷人。当我尝试使用多个目录时,我只会遇到问题。
-
事实上,在第一个函数
traverse_dir()中,我可以列出子目录。
执行程序时出现以下错误。
Traceback (most recent call last):
File "Jenkins.py", line 36, in <module>
filter_apk()
File "Jenkins.py", line 30, in filter_apk
old_xl = pd.read_excel('abc.xlsx')
with open(filename, "rb") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'abc.xlsx'
为什么没有生成文件?有什么建议吗?
修改后的代码
def traverse_dir(rootDir, file_name):
dir_names = []
for names in os.listdir(rootDir):
entry_path = os.path.join(rootDir, names)
if os.path.isdir(entry_path):
dir_names.append(entry_path)
for fil_name in dir_names:
file_path = os.path.join(entry_path, fil_name, file_name)
print(file_path)
if os.path.isfile(file_path):
with open(file_path) as jf:
data = json.load(jf)
df = pd.DataFrame(data)
df1 = pd.DataFrame(data)
new_df = df[df.columns.difference(['SHA256'])]
new_df1 = df1[df.columns.difference(['SHA256'])]
with pd.ExcelWriter('abc.xlsx') as writer:
new_df.to_excel(writer, sheet_name='BRA', index=False)
new_df1.to_excel(writer, sheet_name='CNA', index=False)
else:
raise FileNotFoundError
rootDir = <path to subdirs
file_name = 'installed-files.json'
traverse_dir(rootDir, file_name)
【问题讨论】:
-
错误是关于读取,而不是“生成文件”。该错误表明该文件在它尝试读取的文件夹中不存在,是吗?。
-
没错,因为文件没有生成,所以它没有被读取,因此错误
-
你的代码永远不会调用那个函数,所以它当然永远不会生成!
-
该函数在第二个函数中被调用。
-
不能叫它。调试一下就知道了。
标签: python python-3.x pandas dataframe