path: improve file opening and writing
This commit is contained in:
parent
8fa54b3eaf
commit
fd54ff6d78
|
@ -19,15 +19,23 @@ class Path(str):
|
|||
'exist': exist
|
||||
}
|
||||
|
||||
def __enter__(self):
|
||||
self.fd = self.open('r')
|
||||
return self.fd
|
||||
|
||||
def __new__(cls, content):
|
||||
return str.__new__(cls, content)
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.fd.close()
|
||||
|
||||
|
||||
def __getattr__(self, key):
|
||||
return self.join(key)
|
||||
|
||||
|
||||
def __new__(cls, content):
|
||||
return str.__new__(cls, content)
|
||||
|
||||
|
||||
def __check_dir(self, path=None):
|
||||
target = self if not path else Path(path)
|
||||
|
||||
|
@ -80,6 +88,16 @@ class Path(str):
|
|||
return Path(os.path.join(self, new_path))
|
||||
|
||||
|
||||
def json_load(self):
|
||||
with self as s:
|
||||
return json.load(s)
|
||||
|
||||
|
||||
def json_dump(self, data):
|
||||
with self.open('w') as s:
|
||||
s.write(json.dumps(data))
|
||||
|
||||
|
||||
def link(self, path):
|
||||
target = Path(path)
|
||||
|
||||
|
@ -120,19 +138,13 @@ class Path(str):
|
|||
|
||||
|
||||
def read(self, byte=False):
|
||||
fd = open(self, 'rb' if byte else 'r')
|
||||
data = fd.read()
|
||||
fd.close()
|
||||
|
||||
return data
|
||||
with self.open('rb' if byte else 'r') as fd:
|
||||
return fd.read()
|
||||
|
||||
|
||||
def readlines(self):
|
||||
fd = open(self)
|
||||
data = fd.readlines()
|
||||
fd.close()
|
||||
|
||||
return data
|
||||
with self.open() as fd:
|
||||
return fd.readlines()
|
||||
|
||||
|
||||
def touch(self, mode=0o644, utime=None):
|
||||
|
@ -145,6 +157,11 @@ class Path(str):
|
|||
return self.exists
|
||||
|
||||
|
||||
def write(self, data, mode='w'):
|
||||
with self.open(mode) as fd:
|
||||
fd.write(data)
|
||||
|
||||
|
||||
@property
|
||||
def exists(self):
|
||||
return os.path.exists(self)
|
||||
|
|
Loading…
Reference in a new issue