8.7 연습 문제

8.1

test1 = 'This is a test of the emergency text system'
with open('text.txt', 'w') as f:
f.write(test1)

8.2

test2 = ''
with open('text.txt', 'r') as f:
test2 = f.read()
test1 == test2

True

8.3

import csv
books = '''author,book
J R R Tolkien,THe Hobbit
Lynne Truss,"Eats, Shoots & Leaves"
'''
with open('books.csv', 'wt') as f:
f.write(books)

8.4

with open('books.csv', 'rt') as f:
fin = csv.DictReader(f, fieldnames=['author', 'book'])    
books = [row for row in fin]
books

[OrderedDict([(‘author’, ‘author’), (‘book’, ‘book’)]), OrderedDict([(‘author’, ‘J R R Tolkien’), (‘book’, ‘THe Hobbit’)]), OrderedDict([(‘author’, ‘Lynne Truss’), (‘book’, ‘Eats, Shoots & Leaves’)])]

8.5

books = '''title,author,year
The wriedstone of Brisingamen,Alan Garenr,1960
Perdido Street Statin,China Mieville,2000
Thud!,Terry Pratchett,2005
The Sepllman Files,Lisa Lutz,2007
Small Gods,Terry Pratchett,1992
'''
with open('books.csv', 'wt') as f:
f.write(books)

8.6

import sqlite3
conn = sqlite3.connect('books.db')
curs = conn.cursor()
curs.execute('''CREATE TABLE books
(critter VARCHAR(100),
author VARCHAR(50),
year INT)''')
ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 9))
OperationalError Traceback (most recent call last)
<ipython-input-89-3b86fad18641> in <module>()
4 (critter VARCHAR(100),
5 author VARCHAR(50),
----> 6 year INT)''')

OperationalError: table books already exists
with open('books.csv', 'rt') as f:
fin = csv.DictReader(f, fieldnames=['title', 'author', 'year'])    
books = [row for row in fin]
books
ins = 'INSERT INTO books (critter, author, year) VALUES(?, ?, ?)'
for book in books:
curs.execute(ins, (book['title'], book['author'], book['year']))
OperationalError Traceback (most recent call last)
<ipython-input-101-f2cc359ade70> in <module>()
1 ins = 'INSERT INTO books (critter, author, year) VALUES(?, ?, ?)'
2 for book in books:
----> 3     curs.execute(ins, (book['title'], book['author'], book['year']))

OperationalError: database is locked

8.8, 8.9

curs.execute('SELECT * FROM books ORDER BY critter')
row = curs.fetchall()
row

8.10

import sqlalchemy
conn =  sqlalchemy.create_engine('sqlite:///books.db')
rows = conn.execute('select * from books')
for row in rows:
print(row)

8.11

import redis
conn = redis.Redis()
conn.hmset('test', {'count':1, 'name':'FesterBestertester'})

True

conn.hgetall('test')

{b’count’: b’1’, b’name’: b’FesterBestertester’}

conn.hincrby('test','count', 3)

4

conn.hget('test', 'count')

b’4’

Comments