Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果python中存在文件,如何获取路径?_Python_Python 3.x - Fatal编程技术网

如果python中存在文件,如何获取路径?

如果python中存在文件,如何获取路径?,python,python-3.x,Python,Python 3.x,我有一个名为“main”的文件夹,在main中我还有10个子文件夹(sub1、sub2、.sub10) 每个文件夹都有各种CSV文件 如果子文件夹中存在特定文件,我想获取路径 例如: 如果我正在查找名为“required_file.csv”的文件,并且该文件存在于文件夹(sub1和sub5)中, 我的代码应该会返回给我 paths= ["C\\main\\sub1\\required_file.csv" , "C\\main\\sub5\\required_file

我有一个名为“main”的文件夹,在main中我还有10个子文件夹(sub1、sub2、.sub10)
每个文件夹都有各种CSV文件

如果子文件夹中存在特定文件,我想获取路径

例如:
如果我正在查找名为“required_file.csv”的文件,并且该文件存在于文件夹(sub1和sub5)中, 我的代码应该会返回给我

paths= ["C\\main\\sub1\\required_file.csv" , "C\\main\\sub5\\required_file.csv"]

你试过什么?请分享你的代码你看过了吗?
import os

path_main = 'your_path_here'
filenameToFind = 'your_filename_here'

paths = []
subFolders_list = next(os.walk(path_main))[1]
for subFolder in subFolders_list :
  path = path_main + '/' + subFolder + '/' + filenameToFind # Replace '/' by '\\' if your computer paths are displayed this way
  
  if os.path.isfile(path) : 
    paths.append(path)