1

I want to find a file and open it! Right now I have some problems! Basically, I don't know how to find the file, I know how to find a file in the same directory but not globally on the computer! Can anyone help me? Hier is my code

import os

for root, dirs, files in os.walk(".txt"):
    for filename in files:
        os.startfile(filename)
Skole 13
  • 182
  • 3
  • 12
  • A good place to start might be walking from the root of the file system instead of wherever this is run from. What os are you on? – Evan Apr 10 '19 at 20:16

2 Answers2

1

Reading the fine documentation would be a good place to start. "Globally on the computer" means / slash. Start there, or perhaps in your home directory.

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)
J_H
  • 17,926
  • 4
  • 24
  • 44
0

You can try my answer at:

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

code:

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())
Neeraj Sonaniya
  • 375
  • 4
  • 13