or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdenvironment-loading.mdfile-manipulation.mdindex.mdipython.mdutilities.md

file-manipulation.mddocs/

0

# File Manipulation

1

2

Programmatic functions for reading, writing, and modifying .env files with support for different quote modes and export formats.

3

4

## Capabilities

5

6

### Reading Values

7

8

Retrieve the value of a specific key from a .env file without loading all variables.

9

10

```python { .api }

11

def get_key(

12

dotenv_path: Union[str, os.PathLike[str]],

13

key_to_get: str,

14

encoding: Optional[str] = "utf-8"

15

) -> Optional[str]:

16

"""

17

Get the value of a given key from the given .env file.

18

19

Parameters:

20

dotenv_path: Path to the .env file

21

key_to_get: The key to retrieve

22

encoding: File encoding (default: "utf-8")

23

24

Returns:

25

str or None: Value of the key if found, None if key doesn't exist or has no value

26

"""

27

```

28

29

Usage examples:

30

31

```python

32

from dotenv import get_key

33

34

# Get a specific value

35

database_url = get_key('.env', 'DATABASE_URL')

36

if database_url:

37

print(f"Database URL: {database_url}")

38

39

# Handle missing keys

40

api_key = get_key('.env', 'API_KEY')

41

if api_key is None:

42

print("API_KEY not found in .env file")

43

```

44

45

### Setting Values

46

47

Add or update key/value pairs in .env files with support for different quoting modes and export formats.

48

49

```python { .api }

50

def set_key(

51

dotenv_path: Union[str, os.PathLike[str]],

52

key_to_set: str,

53

value_to_set: str,

54

quote_mode: str = "always",

55

export: bool = False,

56

encoding: Optional[str] = "utf-8"

57

) -> Tuple[Optional[bool], str, str]:

58

"""

59

Add or update a key/value to the given .env file.

60

61

If the .env path given doesn't exist, fails instead of risking creating

62

an orphan .env somewhere in the filesystem.

63

64

Parameters:

65

dotenv_path: Path to the .env file

66

key_to_set: The key to set

67

value_to_set: The value to set

68

quote_mode: Quote mode - "always", "auto", or "never"

69

export: Whether to prefix the line with "export "

70

encoding: File encoding (default: "utf-8")

71

72

Returns:

73

tuple: (success_bool, key, value) where success_bool indicates if operation succeeded

74

75

Raises:

76

ValueError: If quote_mode is not one of "always", "auto", "never"

77

"""

78

```

79

80

Usage examples:

81

82

```python

83

from dotenv import set_key

84

85

# Set a basic key/value pair

86

success, key, value = set_key('.env', 'DATABASE_URL', 'postgresql://localhost/mydb')

87

if success:

88

print(f"Set {key}={value}")

89

90

# Set with different quote modes

91

set_key('.env', 'SIMPLE_KEY', 'simple_value', quote_mode='never') # SIMPLE_KEY=simple_value

92

set_key('.env', 'SPACED_KEY', 'value with spaces', quote_mode='auto') # SPACED_KEY='value with spaces'

93

set_key('.env', 'QUOTED_KEY', 'always_quoted', quote_mode='always') # QUOTED_KEY='always_quoted'

94

95

# Set with export prefix for bash compatibility

96

set_key('.env', 'PATH_VAR', '/usr/local/bin', export=True)

97

# Results in: export PATH_VAR='/usr/local/bin'

98

99

# Handle special characters

100

set_key('.env', 'PASSWORD', "p@ssw0rd'with\"quotes", quote_mode='always')

101

```

102

103

### Removing Values

104

105

Remove keys and their values from .env files.

106

107

```python { .api }

108

def unset_key(

109

dotenv_path: Union[str, os.PathLike[str]],

110

key_to_unset: str,

111

quote_mode: str = "always",

112

encoding: Optional[str] = "utf-8"

113

) -> Tuple[Optional[bool], str]:

114

"""

115

Remove a given key from the given .env file.

116

117

Parameters:

118

dotenv_path: Path to the .env file

119

key_to_unset: The key to remove

120

quote_mode: Quote mode for file operations (currently unused but kept for consistency)

121

encoding: File encoding (default: "utf-8")

122

123

Returns:

124

tuple: (success_bool, key) where success_bool is True if key was removed,

125

None if file doesn't exist or key wasn't found

126

127

Raises:

128

Warning logged if file doesn't exist or key doesn't exist

129

"""

130

```

131

132

Usage examples:

133

134

```python

135

from dotenv import unset_key

136

137

# Remove a key

138

success, key = unset_key('.env', 'OLD_CONFIG_KEY')

139

if success:

140

print(f"Removed {key} from .env file")

141

elif success is None:

142

print("Key not found or file doesn't exist")

143

144

# Remove multiple keys

145

keys_to_remove = ['TEMP_KEY', 'DEPRECATED_SETTING', 'OLD_API_KEY']

146

for key in keys_to_remove:

147

success, removed_key = unset_key('.env', key)

148

if success:

149

print(f"Removed {removed_key}")

150

```

151

152

## Quote Modes

153

154

The `quote_mode` parameter controls how values are quoted in the .env file:

155

156

- **"always"** (default): All values are wrapped in single quotes

157

- **"auto"**: Values containing non-alphanumeric characters are quoted, simple values are not

158

- **"never"**: Values are never quoted (use with caution for values with spaces or special characters)

159

160

Examples:

161

162

```python

163

from dotenv import set_key

164

165

# Different quote modes with the same value

166

value = "hello world"

167

168

set_key('.env', 'KEY1', value, quote_mode='always') # KEY1='hello world'

169

set_key('.env', 'KEY2', value, quote_mode='auto') # KEY2='hello world' (has space)

170

set_key('.env', 'KEY3', value, quote_mode='never') # KEY3=hello world (may cause issues)

171

172

# Auto mode examples

173

set_key('.env', 'SIMPLE', 'abc123', quote_mode='auto') # SIMPLE=abc123 (no quotes)

174

set_key('.env', 'COMPLEX', 'abc-123', quote_mode='auto') # COMPLEX='abc-123' (has hyphen)

175

```

176

177

## Export Mode

178

179

When `export=True` is used with `set_key()`, the resulting line is prefixed with `export `, making the .env file compatible with bash sourcing:

180

181

```python

182

from dotenv import set_key

183

184

set_key('.env', 'PATH_ADDITION', '/usr/local/bin', export=True)

185

# Results in: export PATH_ADDITION='/usr/local/bin'

186

187

# Now the .env file can be sourced in bash:

188

# $ source .env

189

# $ echo $PATH_ADDITION

190

```

191

192

## Error Handling

193

194

The file manipulation functions handle various error conditions:

195

196

- **File doesn't exist**:

197

- `get_key()`: Returns `None` and logs warning with verbose=True

198

- `unset_key()`: Returns `(None, key)` and logs warning

199

- `set_key()`: Raises `IOError` if the file path doesn't exist

200

- **Key doesn't exist**:

201

- `get_key()`: Returns `None` and logs warning with verbose=True

202

- `unset_key()`: Returns `(None, key)` and logs warning

203

- **Invalid quote mode**: `set_key()` raises `ValueError` for modes other than "always", "auto", "never"

204

- **File permissions**: OS-level `PermissionError` and `IOError` exceptions are propagated to caller

205

- **Invalid file encoding**: `UnicodeDecodeError` may be raised if encoding parameter doesn't match file

206

207

Examples of error handling:

208

209

```python

210

from dotenv import get_key, set_key, unset_key

211

212

# Handle missing files

213

try:

214

value = get_key('nonexistent.env', 'KEY')

215

if value is None:

216

print("Key not found or file doesn't exist")

217

except IOError as e:

218

print(f"File access error: {e}")

219

220

# Handle invalid quote modes

221

try:

222

set_key('.env', 'KEY', 'value', quote_mode='invalid')

223

except ValueError as e:

224

print(f"Invalid quote mode: {e}")

225

226

# Handle file creation failure

227

try:

228

set_key('/readonly/path/.env', 'KEY', 'value')

229

except (IOError, PermissionError) as e:

230

print(f"Cannot write to file: {e}")

231

```