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