中文 English

Python 3 I/O Programming

Published: 2021-02-26
python io

File Reading and Writing

read(): reads the entire file at once

with open('/path/to/file', 'r') as f:
    print(f.read())

readlines(): reads one line at a time

for line in f.readlines():
    print(line.strip()) # remove the trailing '\n'

Binary Files

>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # hex representation of bytes

Character Encoding

>>> f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
>>> f.read()
'测试'

Write Files

>>> f = open('/Users/michael/test.txt', 'w')
>>> f.write('Hello, world!')
>>> f.close()

Working with Files and Directories

>>> os.environ
environ({'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'TERM_PROGRAM_VERSION': '326', 'LOGNAME': 'michael', 'USER': 'michael', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin', ...})

# Get environment variable
>>> os.environ.get('PATH')
'/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/mysql/bin'
>>> os.environ.get('x', 'default')
'default'

Working with files and directories

# Absolute path of the current directory:
>>> os.path.abspath('.')
'/Users/michael'
# Build a new directory path:
>>> os.path.join('/Users/michael', 'testdir')
'/Users/michael/testdir'
# Create a directory:
>>> os.mkdir('/Users/michael/testdir')
# Remove a directory:
>>> os.rmdir('/Users/michael/testdir')
>>> os.path.split('/Users/michael/testdir/file.txt')
('/Users/michael/testdir', 'file.txt')

>>> os.path.splitext('/path/to/file.txt')
('/path/to/file', '.txt')

Rename and Delete

# Rename a file:
>>> os.rename('test.txt', 'test.py')
# Delete a file:
>>> os.remove('test.py')
# List all directories in the current directory
>>> [x for x in os.listdir('.') if os.path.isdir(x)]
['.lein', '.local', '.m2', '.npm', '.ssh', '.Trash', '.vim', 'Applications', 'Desktop', ...]

# List all .py files
>>> [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
['apis.py', 'config.py', 'models.py', 'pymonitor.py', 'test_db.py', 'urls.py', 'wsgiapp.py']

Serialization

JSON

# Python object -> JSON
>>> import json
>>> d = dict(name='Bob', age=20, score=88)
>>> json.dumps(d)
'{"age": 20, "score": 88, "name": "Bob"}'

# JSON -> Python object
>>> json_str = '{"age": 20, "score": 88, "name": "Bob"}'
>>> json.loads(json_str)
{'age': 20, 'score': 88, 'name': 'Bob'}

Advanced JSON: class -> JSON

import json

class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score
        
def student2dict(std):
    return {
        'name': std.name,
        'age': std.age,
        'score': std.score
    }
    
def dict2student(d):
    return Student(d['name'], d['age'], d['score'])
    
>>> s = Student('Bob', 20, 88)

>>> print(json.dumps(s, default=student2dict))
{"age": 20, "name": "Bob", "score": 88}
```py
* Advanced JSON, generic method for class -> JSON
``````py
print(json.dumps(s, default=lambda obj: obj.__dict__))