In [ ]:
# 파일읽기
with open("/Users/lucas/test/sample.txt",'r',encoding='utf-8') as file:
all_data = file.read()
#print(all_data)
print(all_data) # 파이썬의 변수 scope 블럭은 함수 안쪽이 아니다.
print("파일 읽기 성공")
In [ ]:
with open("/Users/lucas/test/sample.txt",'r',encoding='utf-8') as file:
a_line=file.readline()
while a_line: # 값이 있으면 True 없으면(None) False
print(a_line)
a_line = line.readline()
In [ ]:
with open("/Users/lucas/test/sample.txt",'r',encoding='utf-8') as file:
a_line=file.readline()
while True: # 값이 있으면 True 없으면(None) False
a_line=file.readline()
if a_line:
print(a_line)
else:
break
In [ ]:
with open("/Users/lucas/test/sample.txt",'r',encoding='utf-8') as file:
a_line=file.readline()
while True: # 값이 있으면 True 없으면(None) False
a_line=file.readline()
if a_line != '':
print(a_line)
else:
break
In [ ]:
with open("/Users/lucas/test/sample.txt",'r',encoding='utf-8') as file:
all_line_list=file.readlines()
#print(all_line_list) # 리스트로 리턴
for line in all_line_list:
print(line)
In [ ]:
def scope_local():
test = 'Hello'
print(test)
scope_local()
In [ ]:
test ='Hello' #전역영역
In [ ]:
def myfunc():
global test # test를 전역변수로
test='World' #로컬영역
print(test)
myfunc() # World
In [ ]:
print(test)
In [ ]:
# 파일쓰기 (덮어쓰기,이어쓰기)
# 덮어쓰기
with open("/Users/lucas/test/myfile.txt",'w',encoding='utf-8') as file:
file.write("11 Neo 01 10k\n")
file.write("12 Morpheus 01 20k\n")
file.write("13 Trinity 01 30k\n")
print('파일에 덮어쓰기 성공')
In [ ]:
# 이어쓰기
with open("/Users/lucas/test/myfile.txt",'a',encoding='utf-8') as file:
file.write("이어쓰기\n")
file.write("11 Neo 01 10k\n")
file.write("12 Morpheus 01 20k\n")
file.write("13 Trinity 01 30k\n")
print('파일에 이어쓰기 성공')
In [ ]:
# File IO, CRUD
# 키보드에서 사원정보 (num,name,dept,sal)를 입력받아서
# Emp 객체에 저장 후에 이용자가 입력을 종료하면
# 지금까지 입력된 모든 사원정보를 파일에 저장하는 기능을 작성해보세요
# 파일에 기록된 후에는 파일로부터 다시 모든 데이터를 읽어서 Emp에 저장하고
# 사원정보 리스트를 화면에 표시홰보세요
In [ ]:
class Employee:
def __init__(self,num,name,dept,sal):
self.num=num
self.name=name
self.dept=dept
self.sal=sal
def __str__(self):
return f'{self.num}\t{self.name}\t{self.dept}\t{self.sal}\n'
In [ ]:
def inputEmp():
kbd=input('num: name: dept: sal:')
[num,name,dept,sal]=kbd.split()
emp = Employee(num,name,dept,sal)
return f'{emp.num}\t{emp.name}\t{emp.dept}\t{emp.sal}\n'
In [ ]:
employeeList=[]
def saveEmp():
while True:
employeeList.append(inputEmp())
if input('계속할까요?')=='x':
with open("/Users/lucas/test/myEmployee.txt",'a',encoding='utf-8') as file:
for emp in employeeList:
file.write(emp)
break
print('파일로 저장성공')
readEmpList=[]
def showEmp():
with open("/Users/lucas/test/myEmployee.txt",'r',encoding='utf-8') as file:
a_line_list=file.readlines()
for i in range(len(a_line_list)):
[num,name,dept,sal]=a_line_list[i].split()
readEmp=Employee(num,name,dept,sal)
readEmpList.append(readEmp)
for readItem in readEmpList:
print(readItem)
In [ ]:
while True:
cmd=input("메뉴를 입력하세요 저장하기(s) 보기(r) 종료(x)")
if cmd=='s':
saveEmp()
elif cmd=='r':
showEmp()
elif cmd=='x':
print("프로그램 종료")
break
In [ ]:
class Emp:
def __init__(self,num,name,dept=0,sal=0):
self.num=num
self.name=name
self.dept=dept
self.sal=sal
def __eq__(self,other):
if(self.num==other.num) and (self.name==other.name):
return True
else:
return False
def __str__(self):
return f'{self.num}\t{self.name}\t{self.dept}\t{self.sal}'
def getStr(self): #인스턴스 메소드
return f'{self.num} {self.name} {self.dept} {self.sal}'
In [ ]:
empList=[]
for _ in range(3):
strInput = input('번호 이름 부서 급여')
[num,name,dept,sal]=strInput.split()
empList.append(Emp(num,name,dept,sal))
In [ ]:
with open("/Users/lucas/test/Emp.txt",'a',encoding='utf-8') as file:
for e in empList:
file.write(e.getStr()+'\n')
print('파일에 저장 성공')
In [ ]:
with open("/Users/lucas/test/Emp.txt",'r',encoding='utf-8') as file:
lineList=file.readlines()
for line in lineList:
[num,name,dept,sal]=line.split()
print(Emp(num,name,dept,sal))
In [ ]:
# 리스트를 문자열로 변환하기
nums = ['1','2','3']
s='ab'.join(nums)
s=''.join(nums)
list(s)
In [ ]:
# Binary 파일 다루기
# 텍스트 파일: 문자가 유니코드(숫자)로 변환되어 저장, 행 구분
# 이진(binary) 파맇 : 헹 구분 없음
In [ ]:
with open('/Users/lucas/test/sample.png', 'rb') as infile:
with open('/Users/lucas/test/sample_cpy_while.png','wb') as outfile:
while True:
data=infile.read(1024) #읽는 크기 1kb
if data:
if len(data) > 0:
outfile.write(data)
else:
break
print("파일 복사 성공")
In [ ]:
with open('/Users/lucas/test/sample.png', 'rb') as infile:
with open('/Users/lucas/test/sample_cpy_class.png','wb') as outfile:
while True:
data=infile.read(1024) #읽는 크기 1kb
if len(data)>0:
outfile.write(data)
else:
break
print("파일 복사 성공")
In [ ]:
#csv 파일 다루기
import csv #표준 파이썬에 없다 아나콘다에서 제공 shell 에서 pip로 설치가능
with open('/Users/lucas/test/cities.csv', encoding='utf-8') as f:
reader=csv.reader(f)
for row in reader:
print(row)
파일을 이용한 CRUD 실습¶
- Product 정보를 입력, 출력, 수정, 삭제, 검색 할 수 있는 기능 작성
- 메뉴 : 목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x)
- 번호, 상품명, 가격, 제조사, 제조일
- 수정기능의 대상속성: 가격, 제조사
- [추가] 기능을 총해서 입력된 데이터는 파일에 저장
- [수정] 기능은 결국 파일에 적용되어야 함
- [삭제] 기능도 파일에 적용
- [목록] 기능은 파일의 데이터를 읽어서 화면에 리스트 출력
In [1]:
class Prod:
def __init__(self,num,name,price=0,company=0,mfd=0):
self.num=num
self.name=name
self.price=price
self.company=company
self.mfd=mfd
def __eq__(self,other):
return (self.num==other.num) and (self.name==other.name)
def __str__(self):
return f'{self.num}\t{self.name}\t{self.price}\t{self.company}\t{self.mfd}'
def getStr(self):
return f'{self.num}\t{self.name}\t{self.price}\t{self.company}\t{self.mfd}'
In [1]:
class Product:
def __init__(self,num,pname, price=0, maker=None, date=None):
self.num = num
self.pname = pname
self.price = price
self.maker = maker
self.date = date
def __str__(self):
return f'{self.num}\t{self.pname}\t{self.price}\t{self.maker}\t{self.date}'
def fstr(self):
return f'{self.num} {self.pname} {self.price} {self.maker} {self.date}'
def __eq__(self, other):
if (self.num==other.num) and (self.pname==other.pname):
return True
else:
return False
In [2]:
def get_list():
pList=[]
with open('/Users/lucas/test/product.txt','r',encoding='utf-8') as file:
line_list = file.readlines()
for line in line_list:
[num,pname,price,maker,date] = line.split()
pList.append( Product(num,pname,price,maker,date) )
return pList
In [3]:
def print_list(pList=[]):
for p in pList:
print(p.fstr())
In [4]:
def print_product(p):
print(p.fstr())
In [5]:
def find():
pname=input('이름으로 검색:')
pList=get_list()
for p in pList:
if p.pname==pname:
return p
In [6]:
def addProduct():
sProd = input('번호 상품명 가격 제조사 제조일:')
[num,pname,price,maker,date]=sProd.split()
p=Product(num,pname,price,maker,date)
with open('/Users/lucas/test/product.txt','a',encoding='utf-8')as file:
file.write(p.fstr()+'\n')
print('상품정보 저장 성공')
In [11]:
def overwrite(pList=[]):
with open('/Users/lucas/test/product.txt','w',encoding='utf-8')as file:
for p in pList:
file.write(p.fstr()+'\n')
print('파일에 저장성공')
In [8]:
def update():
sNumName=input('변경대상 번호 상품명')
[num,pname]=sNumName.split()
p=Product(num,pname)
pList=get_list()
idx=pList.index(p)
newPrice=input('새 가격:')
pList[idx].price=newPrice
overwrite(pList)
print('파일변경 성공')
In [12]:
def delete():
sNumName=input('삭제대상 번호 상품명')
[num,pname]=sNumName.split()
p=Product(num,pname)
print(p.num)
pList=get_list()
idx=pList.index(p)
del pList[idx] #pList.remove(p)
overwrite(pList)
print('삭제 성공')
In [13]:
print('상품 관리 시스템')
while True:
menu = input('목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):')
if menu=='s':
print_list(get_list())
elif menu=='f':
print_product(find())
elif menu=='a':
addProduct()
elif menu=='u':
update()
elif menu=='d':
delete()
elif menu=='x':
break
else:
print('잘못된 메뉴입력')
print('프로그램 종료...')
상품 관리 시스템
목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):d
삭제대상 번호 상품명3 cleat
3
파일에 저장성공
파일에 저장성공
삭제 성공
목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):s
1 football 150 wilson 2022
2 headgear 200 schott 2022
목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):u
변경대상 번호 상품명1 football
새 가격:180
파일에 저장성공
파일에 저장성공
파일변경 성공
목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):s
1 football 180 wilson 2022
2 headgear 200 schott 2022
목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x):x
프로그램 종료...
'자바~하둡' 카테고리의 다른 글
python) socket _ 회원관리 , 3항 연산자, list comprehension (0) | 2022.02.25 |
---|---|
python) Thread pickle socket (0) | 2022.02.24 |
python) List Tuple Set Dictionary 클레스 File IO (0) | 2022.02.22 |
python) List_CRUD (feat. jupyter notebook) (0) | 2022.02.21 |
python) 마크다운, 자료형, 연산자, 형변환, 제어문, 모듈, 튜플, 예외처리,Sliceing (feat. jupyter notebook) (0) | 2022.02.20 |