首页 > 解决方案 > 我编写了一个 python 代码来检查空值并且代码工作正常,但我需要简化代码

问题描述

我想检查有很多子文件夹的 excel 文件中的空值。我编写了一个 python 代码来检查每个文件夹中 excel 文件中的空值,并且代码工作正常,但我需要简化代码。

import os ,uuidtre
import numpy as np
import pandas as pd
import logging


path =r"C:\Users\Documents\python\Emp"

files = os.listdir(path)

for filename in files:
    pathchild=path+'\\'+filename

    file = os.listdir(pathchild)
    files_xls = [f for f in file if f[-4:]== 'xlsx' ]
    child_folders= [f for f in file if f[-4:]!= 'xlsx']


    for f1 in files_xls:
        filepath=pathchild+'\\'+f1
        df = pd.read_excel(filepath, engine='openpyxl')
        count_nan = df.isnull().sum().sum()
        logging.basicConfig(filename='nanTest.log', level=logging.INFO,format='%(message)s')
        if count_nan ==0:
            none=' No none value in the excel file'
        else:
            none=' There is none values founded in the excel file'
        output='File name: '+ f1, 'File path: '+ filepath, none
        logging.info(output)

    for f2 in child_folders:
        patha=pathchild+'\\'+f2
        file1 = os.listdir(patha)
        files_xls1 = [f for f in file1 if f[-4:]== 'xlsx']

        for f3 in files_xls1:
            filechildpath=patha+'\\'+f3
            df = pd.read_excel(filechildpath, engine='openpyxl')
            count_nan   = df.isnull().sum().sum()
            if count_nan ==0:
                none=' No none value in the excel file'
            else:
                none=' There is none values founded in the excel file'

    
            output='File name: '+ f3,'File path: '+ filepath, none
            logging.info(output)

        

标签: python

解决方案


推荐阅读