首页 > 解决方案 > Python:在任何计算机/操作系统上查找 CSV 文件

问题描述

我的名字是塔利辛。我正在做一个学校项目,我必须为此执行多个数据分析。首先,我需要一个代码,它可以按名称在整个计算机中搜索我的文件。目前我有一个代码,我从堆栈溢出的另一个线程借来的,但我需要它也可以在不同的操作系统上工作,比如 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:我怎样才能使用从代码中出来的路径,把它当作csv使用熊猫来阅读?

我对 python 完全陌生。为了我的学习,我通过 Datacamp 学习了基础知识。

感谢您的时间!

标签: pythonpandascsvoperating-systemplatform

解决方案


Mac 是基于 Linux 的操作系统。因此,对于 Mac 和 Linux,您可以使用终端本身的“查找”实用程序。

要搜索特定目录(例如 /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 函数。

希望能帮助到你。


推荐阅读