or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

dict-operations.mddownload-caching.mdfunction-utilities.mdhashing-imports.mdindex.mdlist-operations.mdpath-operations.mdprogress-timing.mdsystem-integration.mdtext-processing.md

path-operations.mddocs/

0

# File and Path Operations

1

2

Cross-platform path utilities, file operations, symbolic links, and temporary directory management with enhanced pathlib functionality.

3

4

## Capabilities

5

6

### Enhanced Path Class

7

8

Extended pathlib.Path with additional methods for common operations.

9

10

```python { .api }

11

class Path(pathlib.Path):

12

"""

13

Enhanced pathlib.Path with additional methods and cross-platform compatibility.

14

"""

15

def augment(self, prefix='', suffix='', ext=None, **kwargs): ...

16

def shrinkuser(self): ...

17

def expanduser(self): ...

18

def ensuredir(self, **kwargs): ...

19

20

def augpath(path, prefix='', suffix='', ext=None, base=None, dpath=None, fname=None, **kwargs):

21

"""

22

Augment path components (directory, filename, extension).

23

24

Args:

25

path (str|Path): Original path

26

prefix (str): Add prefix to filename

27

suffix (str): Add suffix to filename (before extension)

28

ext (str): Change or add file extension

29

base (str): Replace filename base

30

dpath (str): Replace directory path

31

fname (str): Replace entire filename

32

33

Returns:

34

str: Augmented path

35

"""

36

37

def expandpath(path):

38

"""

39

Expand ~ and environment variables in path.

40

41

Args:

42

path (str): Path to expand

43

44

Returns:

45

str: Expanded path

46

"""

47

48

def shrinkuser(path):

49

"""

50

Replace home directory with ~ in path.

51

52

Args:

53

path (str): Path to shrink

54

55

Returns:

56

str: Path with ~ substitution

57

"""

58

59

def userhome():

60

"""

61

Get user home directory.

62

63

Returns:

64

str: User home directory path

65

"""

66

```

67

68

### Directory Operations

69

70

Functions for creating, managing, and working with directories.

71

72

```python { .api }

73

def ensuredir(dpath, mode=0o755, **kwargs):

74

"""

75

Ensure directory exists (mkdir -p equivalent).

76

77

Args:

78

dpath (str|Path): Directory path to create

79

mode (int): Directory permissions (Unix only)

80

**kwargs: Additional options

81

82

Returns:

83

str: The directory path that was ensured

84

"""

85

86

class TempDir:

87

"""

88

Context manager for temporary directories.

89

"""

90

def __init__(self, suffix='', prefix='tmp', dir=None): ...

91

def __enter__(self): ...

92

def __exit__(self, exc_type, exc_val, exc_tb): ...

93

94

@property

95

def dpath(self): ...

96

97

class ChDir:

98

"""

99

Context manager for changing directories.

100

"""

101

def __init__(self, dpath): ...

102

def __enter__(self): ...

103

def __exit__(self, exc_type, exc_val, exc_tb): ...

104

```

105

106

### File Operations

107

108

Basic file manipulation including creation, deletion, and metadata operations.

109

110

```python { .api }

111

def touch(fpath, mode=0o644, dir_fd=None, **kwargs):

112

"""

113

Create empty file or update timestamp.

114

115

Args:

116

fpath (str|Path): File path to touch

117

mode (int): File permissions

118

dir_fd: Directory file descriptor

119

**kwargs: Additional options

120

121

Returns:

122

str: Path of touched file

123

"""

124

125

def delete(fpath, **kwargs):

126

"""

127

Delete file or directory.

128

129

Args:

130

fpath (str|Path): Path to delete

131

**kwargs: Additional options (recursive, etc.)

132

133

Returns:

134

None

135

"""

136

```

137

138

### Symbolic Links

139

140

Cross-platform symbolic link creation with Windows compatibility.

141

142

```python { .api }

143

def symlink(real_path, link_path, overwrite=False, **kwargs):

144

"""

145

Create symbolic link (cross-platform).

146

147

Args:

148

real_path (str|Path): Target path

149

link_path (str|Path): Link path to create

150

overwrite (bool): Overwrite existing link

151

**kwargs: Additional platform-specific options

152

153

Returns:

154

str: Path of created link

155

156

Note:

157

On Windows, may require administrator privileges or developer mode.

158

Falls back to hard links or copying if symbolic links fail.

159

"""

160

```

161

162

### Deprecated I/O Functions

163

164

```python { .api }

165

def readfrom(fpath, **kwargs):

166

"""

167

Read text from file.

168

169

DEPRECATED: Use Path(fpath).read_text() or open() instead.

170

171

Args:

172

fpath (str|Path): File to read

173

**kwargs: Additional options

174

175

Returns:

176

str: File contents

177

"""

178

179

def writeto(fpath, to_write, **kwargs):

180

"""

181

Write text to file.

182

183

DEPRECATED: Use Path(fpath).write_text() or open() instead.

184

185

Args:

186

fpath (str|Path): File to write

187

to_write (str): Content to write

188

**kwargs: Additional options

189

190

Returns:

191

None

192

"""

193

```

194

195

## Usage Examples

196

197

### Path Augmentation

198

199

```python

200

import ubelt as ub

201

202

# Augment path components

203

original = '/home/user/document.txt'

204

205

# Add suffix before extension

206

backup = ub.augpath(original, suffix='_backup')

207

# Result: '/home/user/document_backup.txt'

208

209

# Change extension

210

config = ub.augpath(original, ext='.json')

211

# Result: '/home/user/document.json'

212

213

# Add prefix and change directory

214

new_path = ub.augpath(original, prefix='old_', dpath='/archive')

215

# Result: '/archive/old_document.txt'

216

217

# Multiple modifications

218

result = ub.augpath(original, prefix='backup_', suffix='_v2', ext='.bak')

219

# Result: '/home/user/backup_document_v2.bak'

220

```

221

222

### Temporary Directories

223

224

```python

225

import ubelt as ub

226

227

# Basic temporary directory

228

with ub.TempDir() as tmp:

229

print(f"Temp dir: {tmp.dpath}")

230

231

# Create files in temp directory

232

temp_file = tmp.dpath / 'example.txt'

233

ub.touch(temp_file)

234

235

# Use Path operations

236

temp_path = ub.Path(tmp.dpath)

237

files = list(temp_path.iterdir())

238

print(f"Files: {files}")

239

# Directory is automatically cleaned up

240

241

# Custom temporary directory

242

with ub.TempDir(prefix='myapp_', suffix='_work') as tmp:

243

# Work with temporary directory

244

work_dir = ub.ensuredir(tmp.dpath, 'subdir')

245

config_file = ub.Path(work_dir) / 'config.json'

246

config_file.write_text('{"setting": "value"}')

247

```

248

249

### Directory Management

250

251

```python

252

import ubelt as ub

253

254

# Ensure directory exists

255

project_dir = ub.ensuredir('~/projects/myapp')

256

data_dir = ub.ensuredir(project_dir, 'data')

257

cache_dir = ub.ensuredir(project_dir, 'cache')

258

259

# Change directory context

260

original_dir = ub.Path.cwd()

261

with ub.ChDir('/tmp'):

262

print(f"Current dir: {ub.Path.cwd()}")

263

# Do work in /tmp

264

ub.touch('temp_file.txt')

265

print(f"Back to: {ub.Path.cwd()}") # Back to original directory

266

```

267

268

### File Operations

269

270

```python

271

import ubelt as ub

272

273

# Create empty files

274

ub.touch('new_file.txt')

275

ub.touch('config/settings.ini') # Creates parent dirs if needed

276

277

# Cross-platform symbolic links

278

ub.symlink('/path/to/original', '/path/to/link')

279

280

# Safe deletion

281

try:

282

ub.delete('old_file.txt')

283

ub.delete('old_directory') # Works for directories too

284

except FileNotFoundError:

285

print("File didn't exist")

286

```

287

288

### Cross-Platform Paths

289

290

```python

291

import ubelt as ub

292

293

# Home directory operations

294

home = ub.userhome()

295

config_path = ub.Path(home) / '.config' / 'myapp'

296

297

# Expand user paths

298

expanded = ub.expandpath('~/documents/project')

299

300

# Shrink paths for display

301

display_path = ub.shrinkuser('/home/user/very/long/path')

302

# Result: '~/very/long/path'

303

304

# Enhanced Path class

305

path = ub.Path('~/documents/file.txt').expanduser()

306

parent = path.parent

307

stem = path.stem

308

suffix = path.suffix

309

```

310

311

### Path Validation and Normalization

312

313

```python

314

import ubelt as ub

315

316

# Normalize paths

317

path1 = ub.Path('./documents/../documents/file.txt').resolve()

318

path2 = ub.Path('documents/file.txt').resolve()

319

assert path1 == path2

320

321

# Cross-platform path handling

322

if ub.WIN32:

323

# Windows path handling

324

path = ub.Path('C:\\Users\\Name\\Documents')

325

else:

326

# Unix path handling

327

path = ub.Path('/home/user/documents')

328

329

# Always works regardless of platform

330

normalized = path.expanduser().resolve()

331

```