python - 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 学习了基础知识。
感谢您的时间!
解决方案
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 函数。
希望能帮助到你。
推荐阅读
- python - Unicode_literals(来自 __future__)不适用于 openCV 的 VideoWriter() 中的fourcc 编解码器参数
- python - 变换矩阵 - 显示所有 0 值
- android - 是否可以从任何地方通过语音命令触发您的应用程序?
- java - 如何在下面的嵌套静态类中使用 Context 而不会发生内存泄漏或尝试在空对象引用异常上调用虚拟方法?
- django - 区分 signal.instance 、 Django/signals 中哪个字段发生了变化
- pip - Python2.7-pip 未安装模块
- python - 我想在一个 json 中嵌套三个表并将该 json 传递给 HTML,以便我们可以显示表?
- xcode - Xcode:如何在文件检查器中复制文件?
- c - 使用损坏的顶部大小获取内存内存分配错误
- reactjs - 类中缺少构造函数主体