จะระบุพา ธ ของไฟล์ด้วยวิธีบีบอัดได้อย่างไร?

ฉันต้องการระบุเส้นทางของไฟล์เพื่อจัดเรียงไฟล์ JSON ที่ได้รับจาก API ฉันมีโมดูลคลาสที่บันทึกและโหลดไฟล์

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')

ฉันสงสัยว่าแพรซิสที่ดีที่สุดคืออะไรเมื่อมีที่เก็บที่มีโฟลเดอร์ค่อนข้างคงที่ซึ่งสัมพันธ์กับไดเร็กทอรีการทำงาน ตอนนี้โมดูลทั้งหมดของฉันถูกสร้างขึ้นเพื่อสร้างโฟลเดอร์ที่จำเป็นในพื้นที่เก็บข้อมูลหากไม่มีอยู่ ดังนั้นฉันจึงวางใจได้ว่าเส้นทางนั้นมีอยู่เมื่อโหลดหรือบันทึกไฟล์


person MisterButter    schedule 17.03.2020    source แหล่งที่มา


คำตอบ (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 ของคุณง่ายขึ้น ลองดูสิ!

person N. Wouda    schedule 18.04.2020
comment
ขอบคุณมากสำหรับข้อมูลของคุณ นี่ดูเรียบร้อยมากและคือสิ่งที่ฉันกำลังมองหา! ดีใจที่คุณพบโพสต์ของฉัน ขอบคุณ! - person MisterButter; 19.04.2020