当前位置: 首页>>代码示例>>Python>>正文


Python os.listdir方法代码示例

本文整理汇总了Python中os.listdir方法的典型用法代码示例。如果您正苦于以下问题:Python os.listdir方法的具体用法?Python os.listdir怎么用?Python os.listdir使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.listdir方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: help

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def help():
    print("""
    Usage:
    python weather-icons.py options

    options:
    loop
    image-file.png

    example:
    weather-icons.py loop
    weather-icons.py clear-day.png

    try one of the files from this list:
    {}
    """.format(', '.join(os.listdir(folder_path)))) 
开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:18,代码来源:weather-icons.py

示例2: loop

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def loop():

    print('Looping through all images in folder {}\n'
          'CRL+C to skip image'.format(folder_path))

    try:

        for img_file in os.listdir(folder_path):

            if img_file.endswith(icon_extension):

                print('Drawing image: {}'.format(folder_path + img_file))

                img = Image.open(folder_path + img_file)

                draw_animation(img)

            else:

                print('Not using this file, might be not an image: {}'.format(img_file))

    except KeyboardInterrupt:
        unicorn.off()

    unicorn.off() 
开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:27,代码来源:weather-icons.py

示例3: weather_icons

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def weather_icons():
    try:

        if argv[1] == 'loop':

            loop()

        elif argv[1] in os.listdir(folder_path):

            print('Drawing Image: {}'.format(argv[1]))

            img = Image.open(folder_path + argv[1])

            draw_animation(img)
            unicorn.off()

        else:
            help()

    except IndexError:
        help() 
开发者ID:pimoroni,项目名称:unicorn-hat-hd,代码行数:23,代码来源:weather-icons.py

示例4: readManufacturerSettings

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def readManufacturerSettings(cls, manufacturers, path):
        # pylint: disable=broad-except
        manufacturers = []
        files = [f for f in listdir(path) if isfile(join(path, f))]
        if files:
            for it in files:
                if it.endswith(".obx"):
                    try:
                        manufacturers.append(cls.__parse(os.path.join(path, it)))
                    except Exception as e:
                        print(e)
                        continue

    #
    # Serialize manufacturer from the xml.
    #
    # @param in
    #            Input stream.
    # Serialized manufacturer.
    # 
开发者ID:Gurux,项目名称:Gurux.DLMS.Python,代码行数:22,代码来源:GXManufacturerCollection.py

示例5: score_of_date

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def score_of_date(self, date='2018-08-01'):
        """
        Returns
            tuple: double   score_of_date
                   tuple    info:( title, score)
        """        
        senti_score=0
        articles = os.listdir(os.path.join(self.article_dir, date))
        info = []
        count = 0
        for article in articles:
            if is_cut_file(os.path.join(self.article_dir, date, article)):
                continue
            score, title = self.score_of_article(os.path.join(self.article_dir, date, article))
            senti_score += score
            info.append((title, score))
            count +=1
        return senti_score/len(articles), info 
开发者ID:Coldog2333,项目名称:Financial-NLP,代码行数:20,代码来源:Senti.py

示例6: load_schemas

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def load_schemas(self):
        self.v1_doc_schemas = dict()
        schema_dir = self._get_schema_dir()

        for schema_file in os.listdir(schema_dir):
            f = open(os.path.join(schema_dir, schema_file), 'r')
            for schema in yaml.safe_load_all(f):
                schema_for = schema['metadata']['name']
                if schema_for in self.v1_doc_schemas:
                    self.logger.warning(
                        "Duplicate document schemas found for document kind %s."
                        % schema_for)
                self.logger.debug(
                    "Loaded schema for document kind %s." % schema_for)
                self.v1_doc_schemas[schema_for] = schema.get('data')
            f.close() 
开发者ID:airshipit,项目名称:drydock,代码行数:18,代码来源:deckhand.py

示例7: load_schemas

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def load_schemas(self):
        self.v1_doc_schemas = dict()
        schema_dir = self._get_schema_dir()

        for schema_file in os.listdir(schema_dir):
            f = open(os.path.join(schema_dir, schema_file), 'r')
            for schema in yaml.safe_load_all(f):
                schema_for = schema['metadata']['name']
                if schema_for in self.v1_doc_schemas:
                    self.logger.warning(
                        "Duplicate document schemas found for document kind %s."
                        % schema_for)
                self.logger.debug(
                    "Loaded schema for document kind %s." % schema_for)
                self.v1_doc_schemas[schema_for] = schema
            f.close() 
开发者ID:airshipit,项目名称:drydock,代码行数:18,代码来源:yaml.py

示例8: load_test_cases

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def load_test_cases():
    base_path = os.path.dirname(__file__)
    test_case_path = os.path.join(base_path, "test_cases")
    test_case_files = os.listdir(test_case_path)

    test_cases = []

    for fname in test_case_files:
        if not fname.endswith(".py"):
            continue

        fullpath = os.path.join(test_case_path, fname)
        data = open(fullpath).read()
        tree = ast.parse(data, fullpath)
        codes, messages = extract_expected_errors(data)

        test_cases.append((tree, fullpath, codes, messages))

    return test_cases 
开发者ID:graphql-python,项目名称:gql,代码行数:21,代码来源:test_flake8_linter.py

示例9: load_test_cases

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def load_test_cases():
    base_path = os.path.dirname(__file__)
    test_case_path = os.path.join(base_path, "test_cases")
    test_case_files = os.listdir(test_case_path)

    test_cases = []

    for fname in test_case_files:
        if not fname.endswith(".py"):
            continue

        fullpath = os.path.join(test_case_path, fname)
        data = open(fullpath).read()
        codes, messages = extract_expected_errors(data)
        test_cases.append((fullpath, codes, messages))

    return test_cases 
开发者ID:graphql-python,项目名称:gql,代码行数:19,代码来源:test_pylama_linter.py

示例10: sync_upload

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def sync_upload(rootfs, src, dest):
    fs = Filesystem(rootfs)
    if not fs.implemented():
        return
    print("Adding current directory to the filesystem..")
    with tempfile.TemporaryDirectory() as tmpdirname:
        files = [i for i in os.listdir(".") if i != "arm_now" and not i.startswith("-")]
        if files:
            tar = tmpdirname + "/current_directory.tar"
            subprocess.check_call(["tar", "cf", tar] + files)
            subprocess.check_call("e2cp -G 0 -O 0".split(' ') + [tar, rootfs + ":/"])
            fs.create("/etc/init.d/S95_sync_current_diretory", """
                        cd {dest}
                        tar xf /current_directory.tar
                        rm /current_directory.tar
                        rm /etc/init.d/S95_sync_current_diretory
                        """.format(dest=dest), right=555)

    # TODO: check rootfs fs against parameter injection
    fs.create("/sbin/save", """
                cd {dest}
                tar cf /root.tar *
                sync
                """.format(dest=dest), right=555) 
开发者ID:nongiach,项目名称:arm_now,代码行数:26,代码来源:options.py

示例11: _delete_directory_contents

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def _delete_directory_contents(self, dirpath, filter_func):
        """Delete all files in a directory.

        :param dirpath: path to directory to clear
        :type dirpath: ``unicode`` or ``str``
        :param filter_func function to determine whether a file shall be
            deleted or not.
        :type filter_func ``callable``

        """
        if os.path.exists(dirpath):
            for filename in os.listdir(dirpath):
                if not filter_func(filename):
                    continue
                path = os.path.join(dirpath, filename)
                if os.path.isdir(path):
                    shutil.rmtree(path)
                else:
                    os.unlink(path)
                self.logger.debug('deleted : %r', path) 
开发者ID:TKkk-iOSer,项目名称:wechat-alfred-workflow,代码行数:22,代码来源:workflow.py

示例12: munge

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def munge(src_dir):
    # stored as: ./MCG-COCO-val2014-boxes/COCO_val2014_000000193401.mat
    # want:      ./MCG/mat/COCO_val2014_0/COCO_val2014_000000141/COCO_val2014_000000141334.mat

    files = os.listdir(src_dir)
    for fn in files:
        base, ext = os.path.splitext(fn)
        # first 14 chars / first 22 chars / all chars + .mat
        # COCO_val2014_0/COCO_val2014_000000447/COCO_val2014_000000447991.mat
        first = base[:14]
        second = base[:22]
        dst_dir = os.path.join('MCG', 'mat', first, second)
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        src = os.path.join(src_dir, fn)
        dst = os.path.join(dst_dir, fn)
        print 'MV: {} -> {}'.format(src, dst)
        os.rename(src, dst) 
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:20,代码来源:mcg_munge.py

示例13: main

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def main(cache_dir):
    files_list = list(os.listdir(cache_dir))
    for file in files_list:
        full_filename = os.path.join(cache_dir, file)
        if os.path.isfile(full_filename):
            print("Processing {}".format(full_filename))
            m, stored_kwargs = pickle.load(open(full_filename, 'rb'))
            updated_kwargs = util.get_compatible_kwargs(model.Model, stored_kwargs)

            model_hash = util.object_hash(updated_kwargs)
            print("New hash -> " + model_hash)
            model_filename = os.path.join(cache_dir, "model_{}.p".format(model_hash))
            sys.setrecursionlimit(100000)
            pickle.dump((m,updated_kwargs), open(model_filename,'wb'), protocol=pickle.HIGHEST_PROTOCOL)

            os.remove(full_filename) 
开发者ID:hexahedria,项目名称:gated-graph-transformer-network,代码行数:18,代码来源:update_cache_compatibility.py

示例14: generateDataset

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def generateDataset(self):
        # generate training dataset
        self.FileSequence = []
        self.imgPath = './train/images'
        self.annotationsPath = './train/annotations'
        for subdir in self.trainDatasetPath:
            subdir = os.path.join(subdir,os.listdir(subdir)[0])
            print('trainset >>',subdir)
            self.datasetPath=subdir
            self.generateDatasetFiles()
        self.generateFileSequence('./train')    

        # generate testing dataset
        self.FileSequence = []
        self.imgPath = './test/images'
        self.annotationsPath = './test/annotations'
        for subdir in self.testDatasetPath:
            subdir = os.path.join(subdir,os.listdir(subdir)[0])
            print('testset >>',subdir)
            self.datasetPath=subdir
            self.generateDatasetFiles()    
        self.generateFileSequence('./test')    

        print(self.labels)
        self.generateLabels() 
开发者ID:AmeyaWagh,项目名称:Traffic_sign_detection_YOLO,代码行数:27,代码来源:datasetGenerator.py

示例15: change_name

# 需要导入模块: import os [as 别名]
# 或者: from os import listdir [as 别名]
def change_name(path):
    global i
    if not os.path.isdir(path) and not os.path.isfile(path):
        return False
    if os.path.isfile(path):
        file_path = os.path.split(path)  # 分割出目录与文件
        lists = file_path[1].split('.')  # 分割出文件与文件扩展名
        file_ext = lists[-1]  # 取出后缀名(列表切片操作)
        img_ext = ['bmp', 'jpeg', 'gif', 'psd', 'png', 'jpg']
        if file_ext in img_ext:
            os.rename(path, file_path[0] + '/' + lists[0] + '_fc.' + file_ext)
            i += 1  # 注意这里的i是一个陷阱
        # 或者
        # img_ext = 'bmp|jpeg|gif|psd|png|jpg'
        # if file_ext in img_ext:
        #    print('ok---'+file_ext)
    elif os.path.isdir(path):
        for x in os.listdir(path):
            change_name(os.path.join(path, x))  # os.path.join()在路径处理上很有用 
开发者ID:matiji66,项目名称:face-attendance-machine,代码行数:21,代码来源:rename_file.py


注:本文中的os.listdir方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。