Skip to content

Instantly share code, notes, and snippets.

@mjgpy3
Created March 9, 2016 19:10
Show Gist options
  • Save mjgpy3/bc4fa96e0398d1b89d32 to your computer and use it in GitHub Desktop.
Save mjgpy3/bc4fa96e0398d1b89d32 to your computer and use it in GitHub Desktop.
Python IO Examples
# Simple file IO
```python
with open('somefile.txt', 'w') as file:
file.write('foobar')
with open('somefile.txt', 'r') as file:
text = file.read()
print text
# => foobar
```
# Writing and readin JSON information
```python
import json
structure = {
'name': 'Stephen',
'foods': ['eggs', 'pizza', 'monster']
}
with open('somefile.txt', 'w') as file:
file.write(json.dumps(structure))
with open('somefile.txt', 'r') as file:
you = json.loads(file.read())
print you['name']
# => 'Stephen'
```
# Hand rolled file serialization (don't do this in real life :) )
```python
numbers = [1234, 972315, 2135, 12, 2314, 235, -21]
number_strs = [str(number) for number in numbers]
string = ','.join(number_strs)
print string
with open('number_string.txt', 'w') as f:
f.write(string)
with open('number_string.txt', 'r') as f:
text = f.read()
number_strs2 = text.split(',')
numbers2 = [int(number) for number in number_strs2]
print numbers2
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment