0

I want to open the files in a directory with the following specific file types entered by users:

if type is not None:
    for file in glob.glob(dir + "/" + type):
        if os.path.isfile(file):
            open_file(file)
        if os.path.isdir(file):
            open_folder(file)

Type is "t" as an argument parser variable standing for file types, D is dir:

$ python scan.py -D /home/ -t .php

But it just gives an empty output rather than an expected result with .php files.


Ender phan
  • 185
  • 2
  • 3
  • 10
  • So, your glob statement is `glob.glob('/home//php')` What do you expect this to find? – SiHa Mar 15 '17 at 08:13
  • Try adding a wildcard before the file extension on your glob pattern `glob.glob(dir + '/*.' + type)` – Huy Le Mar 15 '17 at 08:15
  • still empty, I have played around this section , no positive responds given. @HuyLe – Ender phan Mar 15 '17 at 08:26
  • 1
    I suspect you want recursive glob `glob.glob(base_dir + "/**/*." + my_type, recursive=True)` – Huy Le Mar 15 '17 at 08:37
  • @HuyLe it works like a charm. Thanks so much, but it will be my day if you can give a bit explanation about this recursive why I need to you "/**/*." instead – Ender phan Mar 15 '17 at 08:56
  • 1
    You should use `os.path.join` rather than manually concatenating strings. It'll buy you cleaner code and cross platform code, if done correctly. Also using the variable name [`type`](https://docs.python.org/3.6/library/functions.html#type), Its a built in name. – Paul Rooney Mar 15 '17 at 09:08
  • 1
    `**` is the globstar pattern, `**/` will match the current directory and all sub-directories under current path, the rest `*.` is as you expected. `recursive=True` argument is required by python to enable the use of globstar as it implies performance impacts – Huy Le Mar 15 '17 at 09:10

2 Answers2

0

Please try this.

import glob
path = "/home/yourdir/*.php"
for filename in glob.glob(path, recursive=True):
    with open(filename, 'r') as f:
        for line in f:
            print line,

For more Check this.

Community
  • 1
  • 1
Farmer
  • 4,093
  • 3
  • 23
  • 47
  • it's similar scenario but different purposes. The path and type are given by users. My code got stuck when the directory contains so many sub-folders in it, it won't give the file types @Shailesh – Ender phan Mar 15 '17 at 08:30
0

path.py could be what you want.

Install path.py

pip install path.py

And use walkfiles with a pattern.

import path
D = "/home/yourdir"
T = ".php"

for filename in path.Path(D).walkfiles(pattern= "*"+T):
    print(filename)
klim
  • 1,179
  • 8
  • 11