【问题标题】:Access folder with os使用操作系统访问文件夹
【发布时间】:2021-10-11 11:53:11
【问题描述】:

我想使用 for 循环和 os.listdir() 遍历文件夹,我只是想知道在括号中写入什么来访问特定文件。谢谢!

【问题讨论】:

标签: python operating-system


【解决方案1】:

以下示例应该对您有所帮助:

import os

path = "C:/Users/TestDir"
dirs = os.listdir( path )

for file in dirs:
    print(file)

【讨论】:

    【解决方案2】:

    你可以很容易地用谷歌搜索。 https://www.tutorialspoint.com/python/os_listdir.htm 您只需要括号中的路径。

    【讨论】:

      【解决方案3】:

      根据我的理解,您想遍历特定文件夹中的文件,直到找到一个特定文件?你可以这样做:

      import os
      
      FileToBeFound = "Your File Name To Find"
      path = "Path to the directory you would like to check for a file in"
      for file in os.listdir(path):
          if file == FileToBeFound:
              #do stuff with file
              break
          else:
              continue
      

      【讨论】:

        猜你喜欢
        • 2013-06-14
        • 2015-07-16
        • 2011-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多