假设我的python脚本位于“/ main”文件夹中。我在main中的子文件夹中有一堆文本文件。我希望能够通过指定其名称而不是其所在的子目录来打开文件。
所以open_file('test1.csv')应该打开test1.csv,即使它的完整路径是/main/test/test1.csv。 我没有重复的文件名,所以它不应该是一个问题。
我使用的是Windows。
答案 0 :(得分:2)
你可以使用os.walk在子文件夹结构中找到你的文件名
import os
def find_and_open(filename):
for root_f, folders, files in os.walk('.'):
if filename in files:
# here you can either open the file
# or just return the full path and process file
# somewhere else
with open(root_f + '/' + filename) as f:
f.read()
# do something
如果你有一个非常深的文件夹结构,你可能想要限制搜索的深度
答案 1 :(得分:1)
import os
def open_file(filename):
f = open(os.path.join('/path/to/main/', filename))
return f
答案 2 :(得分:1)
import os
def get_file_path(file):
for (root, dirs, files) in os.walk('.'):
if file in files:
return os.path.join(root, file)
这应该有效。它将返回路径,因此您应该在代码中处理打开文件。