0
# File Listing and Information
1
2
Comprehensive file system operations for retrieving directory listings, file metadata, storage information, and directory visualization. Provides structured data access to remote file systems with flexible filtering and formatting options.
3
4
## Capabilities
5
6
### Directory Listing
7
8
List files and directories with detailed metadata, flexible filtering, and depth control for efficient directory traversal.
9
10
```python { .api }
11
def ls(path: str, max_depth: Union[int, None] = None, dirs_only=False,
12
files_only=False, args=None) -> List[Dict[str, Union[int, str]]]:
13
"""
14
Lists files and directories with comprehensive metadata.
15
16
Parameters:
17
- path (str): Directory path to list ('remote:path' for remotes)
18
- max_depth (int, optional): Maximum recursion depth (1 = current directory only)
19
- dirs_only (bool): Return only directories
20
- files_only (bool): Return only files
21
- args (List[str]): Additional rclone lsjson flags
22
23
Returns:
24
List[Dict]: List of file/directory objects with metadata:
25
- Name (str): File or directory name
26
- Path (str): Full path relative to listed directory
27
- Size (int): File size in bytes (0 for directories)
28
- ModTime (str): Last modification time (ISO format)
29
- IsDir (bool): True if directory, False if file
30
- ID (str): Unique file identifier (backend-specific)
31
- MimeType (str): MIME type for files
32
33
Raises:
34
RcloneException: If listing operation fails
35
"""
36
```
37
38
### Storage Information
39
40
Retrieve storage quotas, usage statistics, and backend-specific storage properties.
41
42
```python { .api }
43
def about(path: str) -> Dict:
44
"""
45
Retrieves storage information and quotas for a path.
46
47
Parameters:
48
- path (str): Remote or local path to examine
49
50
Returns:
51
Dict: Storage information containing:
52
- total (int): Total storage capacity in bytes
53
- used (int): Used storage in bytes
54
- free (int): Available storage in bytes
55
- other (int): Other/reserved storage in bytes
56
- objects (int): Number of objects stored
57
- directories (int): Number of directories
58
59
Raises:
60
RcloneException: If about operation fails
61
"""
62
```
63
64
### Directory Statistics
65
66
Calculate total size and file counts for directories and subdirectories.
67
68
```python { .api }
69
def size(path: str, args: List[str] = None) -> Dict:
70
"""
71
Calculates total size and object count for a path.
72
73
Parameters:
74
- path (str): Directory path to analyze
75
- args (List[str]): Additional rclone size flags
76
77
Returns:
78
Dict: Size statistics containing:
79
- count (int): Total number of files
80
- bytes (int): Total size in bytes
81
- sizeless (int): Number of objects without size information
82
83
Raises:
84
RcloneException: If size calculation fails
85
"""
86
```
87
88
### Directory Tree Visualization
89
90
Generate tree-style directory structure visualization for easy navigation and overview.
91
92
```python { .api }
93
def tree(path: str, args: List[str] = None) -> str:
94
"""
95
Generates tree-style directory listing.
96
97
Parameters:
98
- path (str): Root directory path for tree generation
99
- args (List[str]): Additional rclone tree flags
100
101
Returns:
102
str: Tree-formatted directory structure
103
104
Raises:
105
RcloneException: If tree generation fails
106
"""
107
```
108
109
## Usage Examples
110
111
### Basic Directory Listing
112
113
```python
114
from rclone_python import rclone
115
116
# List files in remote directory
117
files = rclone.ls('onedrive:Documents')
118
119
# Print file information
120
for file in files:
121
print(f"Name: {file['Name']}")
122
print(f"Size: {file['Size']} bytes")
123
print(f"Modified: {file['ModTime']}")
124
print(f"Is Directory: {file['IsDir']}")
125
print("---")
126
```
127
128
### Filtered Listings
129
130
```python
131
from rclone_python import rclone
132
133
# List only files (no directories)
134
files_only = rclone.ls('dropbox:Photos', files_only=True)
135
136
# List only directories
137
dirs_only = rclone.ls('box:Projects', dirs_only=True)
138
139
# Shallow listing (current directory only)
140
current_level = rclone.ls('gdrive:Work', max_depth=1)
141
142
# Deep listing with custom depth
143
deep_listing = rclone.ls('onedrive:Archive', max_depth=3)
144
```
145
146
### Storage Information
147
148
```python
149
from rclone_python import rclone
150
151
# Get storage quota and usage
152
storage_info = rclone.about('onedrive:')
153
154
print(f"Total: {storage_info['total'] / (1024**3):.2f} GB")
155
print(f"Used: {storage_info['used'] / (1024**3):.2f} GB")
156
print(f"Free: {storage_info['free'] / (1024**3):.2f} GB")
157
print(f"Files: {storage_info['objects']}")
158
print(f"Directories: {storage_info['directories']}")
159
```
160
161
### Directory Size Analysis
162
163
```python
164
from rclone_python import rclone
165
166
# Calculate directory size
167
size_info = rclone.size('box:Projects/current')
168
169
print(f"Total files: {size_info['count']}")
170
print(f"Total size: {size_info['bytes'] / (1024**2):.2f} MB")
171
172
# Size with additional options
173
detailed_size = rclone.size(
174
'gdrive:Backups',
175
args=['--fast-list'] # Use fast listing for large directories
176
)
177
```
178
179
### Tree Visualization
180
181
```python
182
from rclone_python import rclone
183
184
# Generate directory tree
185
tree_output = rclone.tree('onedrive:Projects')
186
print(tree_output)
187
188
# Tree with custom options
189
detailed_tree = rclone.tree(
190
'dropbox:Archive',
191
args=['--human-readable', '--sort', 'size']
192
)
193
print(detailed_tree)
194
```
195
196
### File Search and Filtering
197
198
```python
199
from rclone_python import rclone
200
201
# Find all Python files in directory tree
202
all_files = rclone.ls('projects:code', files_only=True)
203
python_files = [f for f in all_files if f['Name'].endswith('.py')]
204
205
# Find large files (> 100MB)
206
large_files = [f for f in all_files if f['Size'] > 100 * 1024 * 1024]
207
208
# Find recently modified directories
209
import datetime
210
recent_dirs = []
211
for item in rclone.ls('backup:data', dirs_only=True):
212
mod_time = datetime.datetime.fromisoformat(item['ModTime'].replace('Z', '+00:00'))
213
if (datetime.datetime.now(datetime.timezone.utc) - mod_time).days < 7:
214
recent_dirs.append(item)
215
```
216
217
## File Metadata Structure
218
219
The ls() function returns detailed metadata for each file and directory:
220
221
```python
222
{
223
"Name": str, # File/directory name
224
"Path": str, # Full relative path
225
"Size": int, # Size in bytes (0 for directories)
226
"ModTime": str, # ISO 8601 timestamp
227
"IsDir": bool, # True for directories
228
"ID": str, # Backend-specific unique identifier
229
"MimeType": str, # MIME type (files only)
230
"Tier": str, # Storage tier (if applicable)
231
"IsBucket": bool, # True for bucket-like containers
232
"Hashes": { # Available hashes
233
"md5": str, # MD5 hash (if available)
234
"sha1": str, # SHA1 hash (if available)
235
# ... other hashes
236
}
237
}
238
```
239
240
## Storage Information Structure
241
242
The about() function returns comprehensive storage details:
243
244
```python
245
{
246
"total": int, # Total capacity in bytes
247
"used": int, # Used space in bytes
248
"free": int, # Available space in bytes
249
"other": int, # Reserved/other space in bytes
250
"objects": int, # Total number of objects
251
"directories": int # Total number of directories
252
}
253
```
254
255
## Advanced Usage Patterns
256
257
### Recursive File Processing
258
259
```python
260
from rclone_python import rclone
261
262
def process_directory_recursive(path, callback):
263
"""Process all files in directory tree"""
264
files = rclone.ls(path, files_only=True)
265
for file in files:
266
callback(file)
267
268
def print_file_info(file):
269
print(f"Processing: {file['Path']} ({file['Size']} bytes)")
270
271
# Process all files in remote directory
272
process_directory_recursive('onedrive:Data', print_file_info)
273
```
274
275
### Storage Monitoring
276
277
```python
278
from rclone_python import rclone
279
280
def monitor_storage_usage(remote):
281
"""Monitor storage usage across remotes"""
282
info = rclone.about(f"{remote}:")
283
usage_percent = (info['used'] / info['total']) * 100
284
285
print(f"Storage Usage for {remote}:")
286
print(f" Used: {usage_percent:.1f}%")
287
print(f" Free: {info['free'] / (1024**3):.2f} GB")
288
289
if usage_percent > 90:
290
print(f" WARNING: {remote} is nearly full!")
291
292
# Monitor multiple remotes
293
for remote in ['onedrive', 'dropbox', 'box']:
294
if rclone.check_remote_existing(remote):
295
monitor_storage_usage(remote)
296
```