Py学习  »  Python

python:如何将函数的结果赋给一个可以读取csv的变量

Taliesin R Salomonson • 4 年前 • 456 次点击  

我拥有的代码决定了正在使用的操作系统。然后它必须在整个系统中搜索我的csv文件。当它被发现时,我需要能够读取csv文件(这样它不仅在函数内部,而且在我的代码中都是可用的)。

到目前为止,我能够找到我的文件,但我有困难将文件路径分配给一个变量,这样我就可以用 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 是的。

谢谢你抽出时间。

现在它返回“无”

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46980
 
456 次点击  
文章 [ 1 ]  |  最新文章 4 年前
pissall
Reply   •   1 楼
pissall    4 年前

你没有从任何地方退回任何东西。

我在考虑你的代码是否有效,我已经把必要的 return 打电话但还没有测试:

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])