【问题标题】:How to specify file paths in a compressed way?如何以压缩方式指定文件路径?
【发布时间】:2020-03-17 18:59:04
【问题描述】:

我需要指定文件路径来对从 API 检索到的 JSON 文件进行排序。我有一个保存和加载文件的类模块

import os
import json

class Directory:

    def __init__(self):
        self.working_dir = os.path.dirname(__file__) #Get's the current working directory


    def mkdir(self, *path):
        """Creates folder in the same level as the working directory folder

            Args:
                *args: path to folder that is to be created
        """
        target_dir = os.path.join(self.working_dir, *path)
        try: 
            if os.path.exists(target_dir) == True:
                print(target_dir, 'exists')
            else:
                os.mkdir(os.path.join(self.working_dir, *path))
                print(os.path.join(self.working_dir, *path), 'succesfully created')
        except OSError as e:
            print(folder,'coult not be created', e)

    def check_if_file_exist(self, *path):
        if os.path.exists(os.path.join(self.working_dir, *path)):
            return True
        else:
            return False

    def save_json(self, filename, content, *path):
            """save dictionarirys to .json files        
            Args:
                file (str): The name of the file that is to be saved in .json format
                filename (dict): The dictionary that is to be wrote to the .json file
                folder (str): The folder name in the target directory
            """
            target_dir = os.path.join(self.working_dir, *path)
            file_dir = os.path.join(self.working_dir, target_dir, filename) 
            with open(file_dir + '.json', "w") as f:
                #pretty prints and writes the same to the json file
                f.write(json.dumps(content, indent=4, sort_keys=False))

但是,例如,当必须指定文件路径时,它通常会导致非常长的行。

#EXAMPLE
filename = self.league + '_' + year + '_' + 'fixturestats'
self.dir.save_json(filename, stats, '..', 'json', 'params', 'stats')
path = '/'.join(('..', 'json', 'params'))

#OTHER EXAMPLE
league_season_info = self.dir.load_json('season_params.json', '..', 'json', 'params')

我想知道当拥有一个相对于工作目录具有相当静态文件夹的存储库时,最佳实践是什么。我的所有模块现在都已构建以创建存储库中所需的文件夹(如果它们不存在),因此我可以指望在加载或保存文件时路径存在。

【问题讨论】:

    标签: python repository file-management


    【解决方案1】:

    聚会有点晚了,但我可以这样做。正如您提到的,这些文件夹是相当静态的,它们可以放置到各种配置对象中(例如,作为拥有 dir 的事物的类成员,或独立对象)。因为我不知道你的类结构,所以我会选择一个独立的对象。

    这可能如下所示,使用 pathlib:*

    from pathlib import Path
    
    class StorageConfig:
      STORAGE_BASE_DIR = Path("json")
      PARAMS_DIR = STORAGE_BASE_DIR / "params"
      STATS_DIR = PARAMS_DIR / "stats"
    
      # Etc.
    

    可以这样使用:

    self.dir.save_json(filename, stats, StorageConfig.STATS_DIR)
    params = self.dir.load_json('season_params.json', StorageConfig.PARAMS_DIR)
    

    或者,完全取消目录参数:

    self.dir.save_json(StorageConfig.STATS_DIR / (filename + ".json"), stats)
    params = self.dir.load_json(StorageConfig.PARAMS_DIR / 'season_params.json')
    

    *Pathlib 可以简化Directory 类中当前的大部分代码。看看吧!

    【讨论】:

    • 非常感谢您的意见,这确实看起来很整洁,是我正在寻找的!很高兴你找到我的帖子,谢谢!
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多