FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/native_modules/file_system.py at main · andevsr/pythonnative · GitHub
andevsr
pythonnative
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
native_modules
/
file_system.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
242 lines (198 loc) · 7.49 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
native_modules
/
file_system.py
Copy path
File metadata and controls
242 lines (198 loc) · 7.49 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""Cross-platform app-scoped file I/O.
Provides static helpers for reading, writing, and deleting files in the
app's sandboxed storage area. Relative paths are resolved against
[`FileSystem.app_dir`][pythonnative.native_modules.file_system.FileSystem.app_dir];
absolute paths are used as-is.
Example:
```python
from pythonnative import FileSystem
FileSystem.write_text("notes/today.txt", "Hello, file system!")
print(FileSystem.read_text("notes/today.txt"))
```
"""
import
os
from
typing
import
Any
,
Optional
from
..
import
diagnostics
from
..
utils
import
IS_ANDROID
class
FileSystem
:
"""App-scoped file I/O.
Every instance method operates on either an absolute path or a path
relative to
[`app_dir`][pythonnative.native_modules.file_system.FileSystem.app_dir].
Errors are swallowed and reported as falsy return values (`None`
for readers, `False` for writers) so callers can treat the API as
best-effort.
"""
@
staticmethod
def
app_dir
()
->
str
:
"""Return the app's writable data directory.
On Android the result is `Context.getFilesDir()`. On iOS it is
the user's Documents directory. On a desktop machine without
either runtime, a `.pythonnative_data` directory is created
under the user's home folder.
Returns:
Absolute path to the app's data directory.
"""
if
IS_ANDROID
:
try
:
from
..
utils
import
get_android_context
return
str
(
get_android_context
().
getFilesDir
().
getAbsolutePath
())
except
Exception
:
diagnostics
.
swallowed
(
"file_system.FileSystem.app_dir"
)
else
:
try
:
from
rubicon
.
objc
import
ObjCClass
NSSearchPathForDirectoriesInDomains
=
ObjCClass
(
"NSFileManager"
).
defaultManager
.
URLsForDirectory_inDomains_
docs
=
NSSearchPathForDirectoriesInDomains
(
9
,
1
)
# NSDocumentDirectory, NSUserDomainMask
if
docs
and
docs
.
count
>
0
:
return
str
(
docs
.
objectAtIndex_
(
0
).
path
)
except
Exception
:
diagnostics
.
swallowed
(
"file_system.FileSystem.app_dir"
)
return
os
.
path
.
join
(
os
.
path
.
expanduser
(
"~"
),
".pythonnative_data"
)
@
staticmethod
def
read_text
(
path
:
str
,
encoding
:
str
=
"utf-8"
)
->
Optional
[
str
]:
"""Read a text file.
Args:
path: Absolute path or path relative to
[`app_dir`][pythonnative.native_modules.file_system.FileSystem.app_dir].
encoding: Text encoding (default `"utf-8"`).
Returns:
File contents as a `str`, or `None` if the file cannot be
read.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
with
open
(
full
,
encoding
=
encoding
)
as
f
:
return
f
.
read
()
except
OSError
:
return
None
@
staticmethod
def
write_text
(
path
:
str
,
content
:
str
,
encoding
:
str
=
"utf-8"
)
->
bool
:
"""Write a text file, creating parent directories as needed.
Args:
path: Absolute or `app_dir`-relative path.
content: String to write.
encoding: Text encoding (default `"utf-8"`).
Returns:
`True` on success, `False` on `OSError`.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
os
.
makedirs
(
os
.
path
.
dirname
(
full
),
exist_ok
=
True
)
with
open
(
full
,
"w"
,
encoding
=
encoding
)
as
f
:
f
.
write
(
content
)
return
True
except
OSError
:
return
False
@
staticmethod
def
exists
(
path
:
str
)
->
bool
:
"""Return whether a file or directory exists.
Args:
path: Absolute or `app_dir`-relative path.
Returns:
`True` if the path exists.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
return
os
.
path
.
exists
(
full
)
@
staticmethod
def
delete
(
path
:
str
)
->
bool
:
"""Delete a single file.
Args:
path: Absolute or `app_dir`-relative path.
Returns:
`True` on success, `False` on `OSError`.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
os
.
remove
(
full
)
return
True
except
OSError
:
return
False
@
staticmethod
def
list_dir
(
path
:
str
=
""
)
->
list
:
"""List the entries in a directory.
Args:
path: Absolute or `app_dir`-relative path. Defaults to the
app data directory itself.
Returns:
A list of entry names, or an empty list on error.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
return
os
.
listdir
(
full
)
except
OSError
:
return
[]
@
staticmethod
def
read_bytes
(
path
:
str
)
->
Optional
[
bytes
]:
"""Read a binary file.
Args:
path: Absolute or `app_dir`-relative path.
Returns:
File contents as `bytes`, or `None` if the file cannot be
read.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
with
open
(
full
,
"rb"
)
as
f
:
return
f
.
read
()
except
OSError
:
return
None
@
staticmethod
def
write_bytes
(
path
:
str
,
data
:
bytes
)
->
bool
:
"""Write a binary file, creating parent directories as needed.
Args:
path: Absolute or `app_dir`-relative path.
data: Bytes to write.
Returns:
`True` on success, `False` on `OSError`.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
os
.
makedirs
(
os
.
path
.
dirname
(
full
),
exist_ok
=
True
)
with
open
(
full
,
"wb"
)
as
f
:
f
.
write
(
data
)
return
True
except
OSError
:
return
False
@
staticmethod
def
get_size
(
path
:
str
)
->
Optional
[
int
]:
"""Return file size in bytes.
Args:
path: Absolute or `app_dir`-relative path.
Returns:
File size in bytes, or `None` if the file is missing or
unreadable.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
return
os
.
path
.
getsize
(
full
)
except
OSError
:
return
None
@
staticmethod
def
ensure_dir
(
path
:
str
)
->
bool
:
"""Create a directory (and any missing parents) idempotently.
Args:
path: Absolute or `app_dir`-relative path.
Returns:
`True` on success or if the directory already exists.
"""
full
=
path
if
os
.
path
.
isabs
(
path
)
else
os
.
path
.
join
(
FileSystem
.
app_dir
(),
path
)
try
:
os
.
makedirs
(
full
,
exist_ok
=
True
)
return
True
except
OSError
:
return
False
@
staticmethod
def
join
(
*
parts
:
Any
)
->
str
:
"""Join path components using the OS separator.
Equivalent to `os.path.join(*map(str, parts))`. Provided as a
convenience so callers do not need to import `os.path`
directly.
Args:
*parts: Path components (each coerced to `str`).
Returns:
The joined path string.
"""
return
os
.
path
.
join
(
*
[
str
(
p
)
for
p
in
parts
])
Back
|
FazBrowse Home
|
New Git URL