간단한 터미널 기반 메모장 만들어라
1. 사용자로부터 파일명을 입력받는다.
2. 사용자로부터 파일에 저장할 문장을 입력받아서 파일에 저장한다.
- 한줄씩 입력받는다.
- 사용자가 !q 를 입력하면 저장후 종료한다.
3. 사용자가 저장한 파일을 읽어서 출력한다.
#1. 파일명 입력
filename = input("파일명:")
file_path = os.path.join("files",filename) #file_path를 반복적으로 사용 -> 변수에 저장
print(file_path)
#2. 연결
fw = open(file_path, mode = "wt", encoding = "utf-8")
print("저장할 text를 입력하세요")
#3. !=가 입력될때까지 출력
while True:
line = input(">>>")
if !q == line :
break #
fw.write(line + "\n") #input()은 엔터읽지 x -> 엔터 추가
#fw.write() -> buffer에 저장된 데이터가 close되는 순간 외부자원에 한번에 저장
#fw.flush() -> buffer의 내용을 연결된 자원에 실시간으로 출력
print("종료")
#4. 파일 닫기
fw.close()
os.makedirs("files/test", exist_ok = True)
filename = input("저장할 파일명:")
file_path = os.path.join("files",filename)
#with block 안에 close이전에 수행할 입출력 작성
with open(file_path , mode ="wt", encoding = "utf-8") as fw:
print("저장할 text를 입력하세요")
while True:
line = input(">>>")
if !q == line :
break #
fw.write(line + "\n")
#with block 종료 시 close는 자동으로 처리
print("종료")
def simple_memo() :
os.makedirs("files/test", exist_ok = True)
filename = input("저장할 파일명:")
file_path = os.path.join("files",filename)
#with block 안에 close이전에 수행할 입출력 작성
with open(file_path , mode ="wt", encoding = "utf-8") as fw:
print("저장할 text를 입력하세요")
while True:
line = input(">>>")
if !q == line :
break #
fw.write(line + "\n")
#with block 종료 시 close는 자동으로 처리
print("종료")
1)
%%writefile simple_memo.py
import os #모듈 내부에서 import 필요
def simple_memo():
os.makedirs("files", exist_ok = True)
filename = input("저장할 파일명:")
file_path = os.path.join("files",filename)
#with block 구현
with open(file_path, 'wt',encoding = 'utf-8') as fw :
print("저장할 내용을 입력하세요")
while True :
#한줄 읽기
line_txt = input(">>>")
#!q 입력됐으면 종료
if line_txt == "!q":
break
#파일 출력
fw.write(line_txt + "\n")
#with block 종료시 close는 자동으로 처리
print("종료")
if __name__ == "__main__" :
simple_memo()
2) 모듈 불러오기
from simple_memo import simple_memo as s_memo
3) s_memo()
while True
- 무한 반복, break등을 이용해 중단 조건을 설정해줘야 반복문이 멈춘다.
input은 받은 값을 기본적으로 str 문자열로 변환한다.
반복문 내에 break와 continue
break는 조건문의 내용이 true일때, 해당 반복을 멈춘다. continue는 조건문의 내용이 true에 해당할때만 조건문 다음문장을 실행하지 않고 다음 반복으로 넘어간다.
예) #break
while True:
user_input = input("Do you want to continue? (yes/no): ")
if user_input.lower() == "no":
print("Exiting the loop.")
break
print("Continuing the loop.")
예) #continue
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 == 0:
continue # 짝수인 경우에는 다음 반복으로 건너뜀
print("Odd number:", num)
- member.csv 파일을 읽어서 각 열의 값을 배열에 담는다.
이름,나이,주소 형태의 csv를 읽어 배열에 넣는다.names = [] ages =[] addresses =[]
- 단 첫줄은 head이므로 읽지 않는다. - 참고 함수: 문자열 split(), for문 관련 enumerate()
CSV (Comma Separated Value) 파일
- 데이터들을 정형화(표)된 형태로 텍스트파일에 저장하는 방식
- 행열 데이터 : 행 -데이터 1개 / 열 - 데이터의 속성
- 하나의 데이터는 한줄에 표시. (데이터 구분자는 엔터)
# 각 값들을 저장할 리스트
names = []
ages = []
addresses =[]
# 파일 읽어오기
with open("data/member.csv", "rt", encoding = 'utf-8') as fr :
# 1.데이터를 한 줄씩 읽는다 => for line_txt
## text 데이터는 반복문에서 자동으로 한 줄씩 인식
ex. 5 6 7
9 10 11
=> ["5,6,7\n" ,"9,10,11\n"]
# 1-2. 첫 줄 빼야하니까 인덱스랑 같이 출력
for line_no, line_txt in enumerate(fr) :
if line_no == 0:
continue
# 2. 한 줄에 있는 데이터는 ,로 구분되니 이를 기준으로 나눈다==> split()
##strip() 좌우의 공백 : '' ,엔터, \t,\n 제거
##split() : 기준자를 기준으로 문자열을 분할해 리스트를 반환
# 3. 그 후 속성별로 다른 변수에 할당한다.==> 튜플대입
## 자료구조에 있는 데이터는 대입을 이용해 다른 변수에 담을 수 있다.
name , age, address = line_txt.strip().spilt()
# 4. 속성별로 초기화해둔 리스트에 값을 담는다. ==> .append()
names.append(name)
ages.append(age)
addresses.append(address)
#속성별로 출력
for name,age,address in zip(names,ages,addresses) :
print(f"이름: {name}, 나이:{age}, 지역 {address}")
import pandas as pd
# 파일 불러오기
df = pd.read_csv("data/member.csv")
df
# 속성(columns, 열)별로 불러오기
df["이름"] #dataframe이름[속성명]
df["나이"]
df["주소"]
# 특정 데이터(행) 불러오기 - index로 불러오기
df.loc[1]
>>>
이름 박명수
나이 35
주소 인천