Python:如何将函数的结果分配给我可以读取的变量 [英] Python: How do I assign the result of my function to a variable that i can read_csv

查看:79
本文介绍了Python:如何将函数的结果分配给我可以读取的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有的代码确定使用的是哪个操作系统.然后,它必须在整个系统中搜索我的csv文件.找到它后,我需要能够读取csv文件(以便它不仅在函数内部,而且在整个代码中都可用).

The code that I have determines which Operating System is being used. Then it has to search the entire system for my csv file. When it's found I need to be able to read in the csv file (so that its not just inside the function, but useable throughout my code).

到目前为止,我能够找到我的文件,但是我无法将文件路径分配给变量,因此我可以使用pd.read_csv()

So far I am able to locate my file, but I am having trouble to assign the filepath to a variable, so that I can read in that variabel with pd.read_csv()

我的代码如下:

import pandas as pd
import os
import re
import win32api

# https://stackoverflow.com/questions/13067686/search-files-in-all-drives-using-python
def find_file(root_folder, rex):
        for root,dirs,files in os.walk(root_folder):
            for f in files:
                result = rex.search(f)
                if result:
                    print(os.path.join(root, f))
                    return result
                    break # if you want to find only one

def find_file_in_all_drives(file_name):
        #create a regular expression for the file
        rex = re.compile(file_name)
        for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
           find_file( drive, rex )
        return 

#file_name = "AB_NYC_2019.csv"
#find_file_in_all_drives(file_name)

df_location = find_file_in_all_drives( "AB_NYC_2019.csv" )
df = pd.read_csv(df_location)

我认为return不合适.

谢谢您的时间.

现在它返回"None"

Right now it returns "None"

推荐答案

您从任何地方都没有返回任何东西.

You haven't returned anything from anywhere.

我正在考虑您的代码是否有效,并且已经进行了必要的return调用,但尚未对其进行测试:

I'm considering your code to be working and I've placed the necessary return calls but haven't tested it:

def find_file(root_folder, rex):
    for root, dirs, files in os.walk(root_folder):
        for f in files:
            result = rex.search(f)
            if result:
                file_path = os.path.join(root, f)
                return file_path

def find_file_in_all_drives(file_name):
    matching_files = list()
    # create a regular expression for the file
    rex = re.compile(file_name)
    for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]:
        file_path = find_file(drive, rex)
        if file_path:
            matching_files.append(file_path)
    return matching_files

df_location = find_file_in_all_drives("AB_NYC_2019.csv")
first_file_df = pd.read_csv(df_location[0]) 

这篇关于Python:如何将函数的结果分配给我可以读取的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆