簡體   English   中英

打開文件而不指定子目錄python

[英]Open a file without specifying the subdirectory python

可以說我的python腳本位於文件夾“ / main”中。 我的主子文件夾中有一堆文本文件。 我希望能夠僅通過指定文件名而不是其所在子目錄來打開文件。

因此,即使open_file('test1.csv')的完整路徑為/main/test/test1.csv,也應打開test1.csv。 我沒有重復的文件名,所以應該沒有問題。

我正在使用Windows。

您可以使用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

如果您的文件夾結構很深,則可能需要限制搜索的深度

import os
def open_file(filename):
  f = open(os.path.join('/path/to/main/', filename))
  return f
import os

def get_file_path(file):
    for (root, dirs, files) in os.walk('.'):
        if file in files:
            return os.path.join(root, file)

這應該工作。 它會返回路徑,因此您應該在代碼中處理打開文件的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM