【问题标题】:How to find and then open file with Python如何使用 Python 查找并打开文件
【发布时间】:2019-04-10 20:06:16
【问题描述】:

我想找到一个文件并打开它! 现在我有一些问题! 基本上,我不知道如何找到文件,我知道如何在同一目录中找到文件,但不是在计算机上全局查找!谁能帮我? Hier 是我的代码

import os

for root, dirs, files in os.walk(".txt"):
    for filename in files:
        os.startfile(filename)

【问题讨论】:

  • 一个好的开始可能是从文件系统的根目录开始,而不是从任何地方开始。你在什么操作系统上?

标签: python-3.x python-os


【解决方案1】:

Reading the fine documentation 将是一个很好的起点。 “全局在计算机上”是指/ 斜线。 从那里开始,或者从你的主目录开始。

import os

for root, dirs, files in os.walk('/'):
    for file in files:
        if file.endswith('.txt'):
            filename = os.path.join(root, file)
            os.startfile(filename)

【讨论】:

    【解决方案2】:

    你可以试试我的回答:

    https://stackoverflow.com/questions/2212643/python-recursive-folder-read/55193831#55193831
    

    代码:

    import glob
    import os
    
    root_dir = <root_dir_here>
    
    for filename in glob.iglob(root_dir + '**/**', recursive=True):
        if os.path.isfile(filename):
            with open(filename,'r') as file:
                print(file.read())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 2019-03-31
      • 2014-04-26
      相关资源
      最近更新 更多