File 처리

파일 쓰기


In [1]:
f = open('myfile.txt', 'w')

In [2]:
f.write('python file test')


Out[2]:
16

In [3]:
f.close()

파일 읽기


In [4]:
f = open('myfile.txt', 'r')

In [5]:
f.read()


Out[5]:
'python file test'

In [6]:
f.read()


Out[6]:
''

파일의 맨 처음으로 이동


In [7]:
f.seek(0)


Out[7]:
0

In [8]:
f.read(3)


Out[8]:
'pyt'

파일을 한줄씩 읽기


In [9]:
f.readline()


Out[9]:
'hon file test'

In [10]:
f.seek(0)


Out[10]:
0

파일 여러줄을 한꺼번에 읽기


In [11]:
f.readlines()


Out[11]:
['python file test']

In [12]:
f.close()

with 문을 이용한 파일 핸들링


In [13]:
with open('myfile.txt') as f:
    for line in f:
        print(line)


python file test

CSV 모듈을 이용한 파일 처리


In [14]:
import csv

In [15]:
with open('myfile.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows([['age', 'blood'], [10, 'A'], [20, 'B']])

In [16]:
with open('myfile.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)


['age', 'blood']
['10', 'A']
['20', 'B']

In [17]:
with open('myfile.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['age'], row['blood'])


10 A
20 B

JSON 모듈을 이용한 파일 처리


In [18]:
import json

In [19]:
menu = """[
            { "id": 1001, "type": "Regular" },
            { "id": 1002, "type": "Chocolate" },
            { "id": 1003, "type": "Blueberry" },
            { "id": 1004, "type": "Devil's Food" }
        ]"""

In [20]:
obj = json.loads(menu)
obj


Out[20]:
[{'id': 1001, 'type': 'Regular'},
 {'id': 1002, 'type': 'Chocolate'},
 {'id': 1003, 'type': 'Blueberry'},
 {'id': 1004, 'type': "Devil's Food"}]

In [21]:
json.dumps(obj)


Out[21]:
'[{"id": 1001, "type": "Regular"}, {"id": 1002, "type": "Chocolate"}, {"id": 1003, "type": "Blueberry"}, {"id": 1004, "type": "Devil\'s Food"}]'

In [ ]: