从目录访问文件

时间:2018-11-03 10:58:16

标签: python-3.x

我在下面指定了2个目录

\src - contains my .py file
\data - contains data to be accessed by .py file.

无论.py正在执行什么系统,我都希望它从\ data中拾取文件。

怎么可能?

2 个答案:

答案 0 :(得分:0)

我不确定您要访问哪种文件(即文件类型),但是如果您希望无论主py文件的位置如何都不要更改路径,

\ data 中打开终端,并使用以下命令获取工作目录:

function getName($id){ $stmt = $this->con->prepare("SELECT name, teamaffiliation as team FROM heroes WHERE id = ?"); $stmt->bind_param("i", $id); $stmt->execute(); $stmt->bind_result($name, $team); $heroes = array(); while($stmt->fetch()){ $hero = array(); $hero['name'] = $name; $hero['team'] = $team; array_push($heroes, $hero); } return $heroes; }

这就是您将使用的文件路径:即/opt/stuff/file.json

答案 1 :(得分:0)

根据我对您的问题的了解,您可以提及根文件夹,然后遍历目录结构。 os.walk()是实现它的方式。您可以找到文档here

但是您必须遍历整个目录树,直到找到'/ data'。

您必须加入当前目录和名称才能获取文件的绝对路径

os.path.join(root, name)

示例代码段

import os
for root, dirs, files in os.walk("/var/log"):
    print root
    print dirs
    print files