0
# Filesystem Operations
1
2
Filesystem operations in pyparted provide capabilities for detecting, probing, and managing filesystem types on partitions. These operations help identify existing filesystems and set appropriate filesystem types for partitions.
3
4
## Capabilities
5
6
### Filesystem Probing Functions
7
8
Functions for detecting and identifying filesystems on storage regions.
9
10
```python { .api }
11
def probeFileSystem(geometry: Geometry) -> str:
12
"""
13
Detect filesystem type in the specified geometry region.
14
15
Args:
16
geometry (Geometry): Region to probe for filesystem
17
18
Returns:
19
str: Filesystem type name if detected, None if no filesystem found
20
21
Raises:
22
GeometryException: If geometry is invalid
23
"""
24
25
def probeForSpecificFileSystem(fstype: str, geometry: Geometry) -> Geometry:
26
"""
27
Probe for specific filesystem type and return its exact geometry.
28
29
Args:
30
fstype (str): Filesystem type to probe for
31
geometry (Geometry): Region to search within
32
33
Returns:
34
Geometry: Exact geometry of filesystem if found
35
36
Raises:
37
FileSystemException: If filesystem type is invalid
38
GeometryException: If geometry is invalid
39
"""
40
```
41
42
### FileSystem Class
43
44
The FileSystem class represents a filesystem with its properties and location.
45
46
```python { .api }
47
class FileSystem:
48
"""
49
FileSystem represents a filesystem on a storage device.
50
Contains filesystem type and geometry information.
51
"""
52
53
# Read-only properties
54
type: str # Filesystem type name (e.g., 'ext4', 'ntfs', 'fat32')
55
geometry: Geometry # Geometry region containing filesystem
56
checked: bool # Whether filesystem was checked during creation
57
```
58
59
### FileSystem Creation
60
61
Constructor for creating filesystem objects.
62
63
```python { .api }
64
class FileSystem:
65
def __init__(type: str, geometry: Geometry, checked: bool = False) -> FileSystem:
66
"""
67
Create new filesystem object.
68
69
Args:
70
type (str): Filesystem type name
71
geometry (Geometry): Geometry region for filesystem
72
checked (bool): Whether filesystem should be marked as checked
73
74
Raises:
75
FileSystemException: If type is invalid
76
GeometryException: If geometry is invalid
77
"""
78
```
79
80
## Filesystem Types
81
82
Access to available filesystem types through the global `fileSystemType` dictionary.
83
84
```python { .api }
85
# Global filesystem type registry
86
fileSystemType: dict[str, object] # Maps filesystem names to type objects
87
```
88
89
Common filesystem types supported by pyparted:
90
91
- **Linux Filesystems**: ext2, ext3, ext4, xfs, btrfs, reiserfs
92
- **Windows Filesystems**: ntfs, fat16, fat32, exfat
93
- **Network Filesystems**: nfs
94
- **Other Filesystems**: hfs, hfs+, ufs, swap
95
96
## Usage Examples
97
98
### Detecting Existing Filesystems
99
100
```python
101
import parted
102
103
device = parted.getDevice('/dev/sda')
104
disk = parted.newDisk(device)
105
106
print("Scanning partitions for filesystems:")
107
for partition in disk.partitions:
108
if partition.fileSystem:
109
# Filesystem detected during partition table read
110
print(f"Partition {partition.number}: {partition.fileSystem.type}")
111
else:
112
# Probe for filesystem manually
113
try:
114
fs_type = parted.probeFileSystem(partition.geometry)
115
if fs_type:
116
print(f"Partition {partition.number}: {fs_type} (probed)")
117
else:
118
print(f"Partition {partition.number}: No filesystem detected")
119
except Exception as e:
120
print(f"Partition {partition.number}: Error probing - {e}")
121
```
122
123
### Probing Specific Filesystem Types
124
125
```python
126
import parted
127
128
device = parted.getDevice('/dev/sdb')
129
partition_geometry = parted.Geometry(device, start=2048, length=2097152) # 1GB
130
131
# Probe for specific filesystems
132
filesystem_types = ['ext4', 'ntfs', 'fat32', 'xfs']
133
134
for fs_type in filesystem_types:
135
try:
136
detected_geometry = parted.probeForSpecificFileSystem(fs_type, partition_geometry)
137
if detected_geometry:
138
print(f"Found {fs_type} filesystem:")
139
print(f" Start: {detected_geometry.start}")
140
print(f" Length: {detected_geometry.length}")
141
print(f" End: {detected_geometry.end}")
142
break
143
except parted.FileSystemException:
144
continue # Filesystem type not found
145
except Exception as e:
146
print(f"Error probing for {fs_type}: {e}")
147
else:
148
print("No recognized filesystem found")
149
```
150
151
### Creating FileSystem Objects
152
153
```python
154
import parted
155
156
device = parted.getDevice('/dev/sdc')
157
158
# Create geometry for filesystem
159
fs_geometry = parted.Geometry(device, start=2048, length=4194304) # 2GB
160
161
# Create filesystem objects for different types
162
ext4_fs = parted.FileSystem('ext4', fs_geometry, checked=True)
163
ntfs_fs = parted.FileSystem('ntfs', fs_geometry, checked=False)
164
165
print(f"ext4 filesystem: type={ext4_fs.type}, checked={ext4_fs.checked}")
166
print(f"ntfs filesystem: type={ntfs_fs.type}, checked={ntfs_fs.checked}")
167
168
# Use filesystem with partition
169
disk = parted.newDisk(device)
170
partition = parted.Partition(
171
disk=disk,
172
type=parted.PARTITION_NORMAL,
173
geometry=fs_geometry,
174
fs=ext4_fs
175
)
176
177
print(f"Partition filesystem: {partition.fileSystem.type}")
178
```
179
180
### Setting Partition Filesystem Types
181
182
```python
183
import parted
184
185
device = parted.getDevice('/dev/sdb')
186
disk = parted.newDisk(device)
187
188
# Find partition to modify
189
partition = disk.getPartitionByNumber(1)
190
if partition:
191
# Create filesystem object for desired type
192
new_geometry = partition.geometry
193
new_filesystem = parted.FileSystem('ext4', new_geometry)
194
195
# Set filesystem type on partition
196
partition.setSystem(new_filesystem)
197
198
# Commit changes
199
disk.commit()
200
201
print(f"Set partition {partition.number} filesystem type to ext4")
202
else:
203
print("Partition not found")
204
```
205
206
### Comprehensive Filesystem Detection
207
208
```python
209
import parted
210
211
def detect_all_filesystems(device_path):
212
"""Detect all filesystems on a device."""
213
device = parted.getDevice(device_path)
214
disk = parted.newDisk(device)
215
216
results = []
217
218
for partition in disk.partitions:
219
partition_info = {
220
'number': partition.number,
221
'path': partition.path,
222
'size_gb': partition.getSize('GB'),
223
'filesystem': None
224
}
225
226
# First check if filesystem is already detected
227
if partition.fileSystem:
228
partition_info['filesystem'] = partition.fileSystem.type
229
else:
230
# Probe for filesystem
231
try:
232
fs_type = parted.probeFileSystem(partition.geometry)
233
partition_info['filesystem'] = fs_type or 'Unknown'
234
except Exception as e:
235
partition_info['filesystem'] = f'Error: {e}'
236
237
results.append(partition_info)
238
239
return results
240
241
# Use the function
242
device_path = '/dev/sda'
243
filesystems = detect_all_filesystems(device_path)
244
245
print(f"Filesystems on {device_path}:")
246
for info in filesystems:
247
print(f" {info['path']}: {info['filesystem']} ({info['size_gb']:.1f} GB)")
248
```
249
250
### Filesystem Type Validation
251
252
```python
253
import parted
254
255
# Check available filesystem types
256
print("Available filesystem types:")
257
for fs_name in sorted(parted.fileSystemType.keys()):
258
print(f" {fs_name}")
259
260
# Validate filesystem type before use
261
def is_valid_filesystem_type(fs_type):
262
return fs_type in parted.fileSystemType
263
264
# Test filesystem types
265
test_types = ['ext4', 'ntfs', 'invalid_type', 'fat32']
266
for fs_type in test_types:
267
valid = is_valid_filesystem_type(fs_type)
268
print(f"{fs_type}: {'Valid' if valid else 'Invalid'}")
269
```
270
271
### Partition Creation with Filesystem
272
273
```python
274
import parted
275
276
device = parted.getDevice('/dev/sdd')
277
278
# Create fresh partition table
279
disk = parted.freshDisk(device, 'gpt')
280
281
# Create constraint for operations
282
constraint = device.getOptimalAlignedConstraint()
283
284
# Create geometry for new partition
285
start_sector = 2048
286
size_sectors = (50 * 1024**3) // device.sectorSize # 50GB
287
geometry = parted.Geometry(device, start=start_sector, length=size_sectors)
288
289
# Create filesystem object
290
filesystem = parted.FileSystem('ext4', geometry)
291
292
# Create partition with filesystem
293
partition = parted.Partition(
294
disk=disk,
295
type=parted.PARTITION_NORMAL,
296
geometry=geometry,
297
fs=filesystem
298
)
299
300
# Add partition and commit
301
disk.addPartition(partition, constraint)
302
disk.commit()
303
304
print(f"Created partition with ext4 filesystem at {partition.path}")
305
```
306
307
### Error Handling in Filesystem Operations
308
309
```python
310
import parted
311
312
def safe_filesystem_probe(geometry):
313
"""Safely probe for filesystem with error handling."""
314
try:
315
fs_type = parted.probeFileSystem(geometry)
316
return fs_type if fs_type else "No filesystem"
317
except parted.FileSystemException as e:
318
return f"Filesystem error: {e}"
319
except parted.GeometryException as e:
320
return f"Geometry error: {e}"
321
except Exception as e:
322
return f"Unknown error: {e}"
323
324
device = parted.getDevice('/dev/sda')
325
disk = parted.newDisk(device)
326
327
for partition in disk.partitions:
328
result = safe_filesystem_probe(partition.geometry)
329
print(f"Partition {partition.number}: {result}")
330
```
331
332
## Filesystem Detection Limitations
333
334
### Important Notes
335
336
1. **Read-Only Detection**: pyparted can detect existing filesystems but cannot create or format them
337
2. **Type Setting Only**: `setSystem()` only sets the partition's filesystem type hint, it doesn't format
338
3. **Probe Accuracy**: Filesystem probing may not detect all filesystem types or corrupted filesystems
339
4. **No Filesystem Operations**: pyparted doesn't provide filesystem resize, check, or repair operations
340
341
### External Tools Integration
342
343
For actual filesystem operations, use external tools:
344
345
```python
346
import subprocess
347
import parted
348
349
def format_partition(partition_path, fs_type):
350
"""Format partition using external tools (example - be careful!)."""
351
format_commands = {
352
'ext4': ['mkfs.ext4', '-F', partition_path],
353
'ntfs': ['mkfs.ntfs', '-f', partition_path],
354
'fat32': ['mkfs.vfat', '-F32', partition_path],
355
'xfs': ['mkfs.xfs', '-f', partition_path]
356
}
357
358
if fs_type in format_commands:
359
try:
360
subprocess.run(format_commands[fs_type], check=True)
361
print(f"Formatted {partition_path} as {fs_type}")
362
except subprocess.CalledProcessError as e:
363
print(f"Format failed: {e}")
364
else:
365
print(f"Unsupported filesystem type: {fs_type}")
366
367
# WARNING: This destroys data! Use with extreme caution.
368
# format_partition('/dev/sdb1', 'ext4')
369
```
370
371
## Filesystem Types Reference
372
373
### Linux Filesystems
374
- **ext2, ext3, ext4**: Extended filesystems (ext4 recommended)
375
- **xfs**: High-performance journaling filesystem
376
- **btrfs**: B-tree filesystem with advanced features
377
- **reiserfs**: Journaling filesystem (deprecated)
378
379
### Windows Filesystems
380
- **ntfs**: Windows NT filesystem
381
- **fat16, fat32**: File Allocation Table filesystems
382
- **exfat**: Extended File Allocation Table
383
384
### Special Filesystems
385
- **swap**: Linux swap space
386
- **linux-swap**: Linux swap partition
387
- **hfs, hfs+**: Apple Hierarchical File System