withas.md 1.7 KB
Newer Older
F
feilong 已提交
1 2 3 4 5
# Python with-as 语句(1)

JSON文件读写

```python
F
feilong 已提交
6
# -*- coding: UTF-8 -*-
F
feilong 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
import json

def load_json(file):
    # TODO(You): 实现加载json文件代码

def dump_json(file, obj):
    # TODO(You): 实现将dict写入json文件的代码

if __name__ == '__main__':
    data = {
        'test': 1,
    }
    dump_json('test.json', data)
    load_json('test.json')
```

请选出下列能**正确**实现这一功能的选项。

## template

```python

import json


def load_json(file):
    with open(file, 'r') as f:
        return json.loads(f.read())


def dump_json(file, obj):
    with open(file, 'w') as f:
        f.write(json.dumps(obj, indent=2, ensure_ascii=False))

if __name__ == '__main__':
    data = {
        'test': 1,
    }
    dump_json('test.json', data)
    load_json('test.json')
```

## 答案

```python
def load_json(file):
    with open(file, 'r') as f:
        return json.loads(f.read())

def dump_json(file, obj):
    with open(file, 'w') as f:
        f.write(json.dumps(obj, indent=2, ensure_ascii=False))
```

## 选项

### A

```python
def load_json(file):
    with open(file, 'w') as f:
        return json.loads(f.read())

def dump_json(file, obj):
    with open(file, 'r') as f:
        f.write(json.dumps(obj, ensure_ascii=False, indent=2))
```

### B

```python
def load_json(file):
    with open(file, 'w') as f:
        return json.loads(f.read())

def dump_json(file, obj):
    with open(file, 'r') as f:
        f.write(json.dumps(obj, indent=2, ensure_ascii=False))
```

### C

```python
def load_json(file):
    with open(file, 'r') as f:
        return json.loads(f.read())

def dump_json(file, obj):
    with open(file, 'w') as f:
        f.write(json.dumps(obj, ensure_ascii=False, indent=2))
```