> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/prog/python/file-handling.md).

# File Handling

## Simple examples

### Write binary data to file

One way to write to a file

```python
f = open(filename, 'wb')
f.write(data)
f.close()
```

Another way

```python
with open(filename, 'wb') as fd:
    fd.write(data)
```

### Prepend GIF-header to standard web shell

```python
std_shell_filename = 'get_pw.php'
new_shell_filename = 'get_pw_gif.php'
new_shell = open(new_shell_filename, 'wb')
gif_header = '47 49 46 38 39 61'
new_shell.write(bytes.fromhex(gif_header))
with open(std_shell_filename, 'rb') as std_shell:
    std_shell_data = std_shell.read()
    new_shell.write(std_shell_data)
new_shell.close()
```

## Resources

File and Directory Access - Python: <https://docs.python.org/3/library/filesys.html>

Reading and Writing Files - Python: <https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files>
