[英]Python: How do I assign the result of my function to a variable that i can read_csv
我拥有的代码确定正在使用哪个操作系统。 然后它必须在整个系统中搜索我的 csv 文件。 当它被发现时,我需要能够读取 csv 文件(这样它不仅在 function 中,而且在我的代码中都可以使用)。
到目前为止,我能够找到我的文件,但是我无法将文件路径分配给一个变量,以便我可以使用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
有什么不对劲的地方。
感谢您的时间。
现在它返回“无”
你没有从任何地方返回任何东西。
我正在考虑您的代码正在运行,并且我已经发出了必要的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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.