Combining file and directory selection options

◇◆丶佛笑我妖孽 提交于 2019-12-12 06:26:54

问题


I would like to combine the functionality of two arguments to one. Currently -f may be used to specify a single file or wild-card, -d may specify a directory. I would like -f to handle its currently functionality or a directory.

Here's the current options statements:

parser.add_option('-d', '--directory',
        action='store', dest='directory',
        default=None, help='specify directory')
parser.add_option('-f', '--file',
        action='store', dest='filename',
        default=None, help='specify file or wildcard')
if len(sys.argv) == 1:
    parser.print_help()
    sys.exit()
(options, args) = parser.parse_args()

Here is the logic in the functionality, can these be combined?

filenames_or_wildcards = []

# remove next line if you do not want allow to run the script without the -f -d
# option, but with arguments
filenames_or_wildcards = args # take all filenames passed in the command line

# if -f was specified add them (in current working directory)
if options.filename is not None:
    filenames_or_wildcards.append(options.filename)

# if -d was specified or nothing at all add files from dir
if options.directory is not None:
    filenames_or_wildcards.append( os.path.join(options.directory, "*") )

# Now expand all wildcards
# glob.glob transforms a filename or a wildcard in a list of all matches
# a non existing filename will be 'dropped'
all_files = []
for filename_or_wildcard in filenames_or_wildcards:
    all_files.extend( glob.glob(filename_or_wildcard) )

回答1:


You can pass a list of wildcards, directories and files to this function. However, your shell will expand your wildcards if you do not put them between quotes in the command line.

import os
import glob

def combine(arguments):
    all_files = []
    for arg in arguments:
        if '*' in arg or '?' in arg:
            # contains a wildcard character
            all_files.extend(glob.glob(arg))
        elif os.path.isdir(arg):
            # is a dictionary
            all_files.extend(glob.glob(os.path.join(arg, '*')))
        elif os.path.exists(arg):
            # is a file
            all_files.append(arg)
        else:
            # invalid?
            print '%s invalid' % arg
    return all_files


来源:https://stackoverflow.com/questions/5380279/combining-file-and-directory-selection-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!