我叫Taliesin。我正在做一个学校项目,我必须为此执行多个数据分析。首先,我需要一个代码,通过名称在整个计算机上搜索我的文件。目前,我有一个代码,该代码是我从Stack溢出的另一个线程借来的,但是我需要它也可以在不同的操作系统(如mac)上工作。同样,使用我现在使用的代码,我也不知道如何将结果转换为可以使用pd.read_csv()打开的内容。
到目前为止,这是我的代码:
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))
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 )
find_file_in_all_drives( "AB_NYC_2019.csv" )
df_location = find_file_in_all_drives( "AB_NYC_2019.csv" )
df = pd.read_csv(r'"{}"'.format(df_location))
因此,总结一下我的问题:1:如何更改代码,使其可在任何平台上运行?2:如何使用代码中的路径,并使用pandas将其读取为csv?
我对python完全陌生。我通过Datacamp学习了基础知识。
谢谢您的时间!
Mac是基于Linux的操作系统。因此,对于Mac和Linux,您可以从终端本身使用'find'实用程序。
搜索特定目录(例如/ home / project / csv)-
find /home/project/csv | grep "AB_NYC_2019.csv"
搜索整个文件系统-
find / | grep "AB_NYC_2019.csv"
但是,如果您仍然希望将其作为python程序的一部分,则可以运行
import subprocess
paths = [line.decode("utf-8") for line in subprocess.check_output("find /home/project/csv | grep 'AB_NYC_2019.csv'", shell=True)]
这将在搜索目录中找到所有此类文件,并返回其路径列表。
[确定您的python程序在哪个系统上运行,
import platform
platform.system()
#Darwin - for Mac OS
#Linux - for Linux
#Windows - for Windows
您可以在platform.system()的值上设置if条件,并相应地运行任一find函数。
希望有帮助。