Day6 File 입/출력, 모듈
- 파일 입출력
f = open('파일경로', '모드')
f.close()
상대경로 / 절대경로
모드
모드 |
설명 |
w |
write 모드 파일 전체에 새로 쓰기 |
r |
read 모드 파일을 읽는 모드 |
a |
append 모드 파일에 내용을 추가하는 모드 |
[ Tip ] Whitespace Character
\n or \n
\t or \t
(ex) print("Hello \n I'm Jane.")
파일 예제
f = open("./hello.txt", "w") // .는 현재폴더 의미함 f.write("Hellow Wrold!")
f.close() |
f = open("./hello.txt", "a")
for i in range(2, 10+1): content = '\n' + str(i) + "번째 줄입니다." f.write(content)
f.close() |
f = open("./hello.txt", "r")
content = f.read() print(content) f.seek(0) // 0번째 글자로 커서 이동
f.close
# 한 줄씩 읽기
f = open("./hello.txt", "r")
content = f.readline() print(f.readline()) # 커서는 읽어들인 줄 맨 마지막에 위치
f.close()
|
연습
파일 만들고 읽어오기
- 파일을 만들어서 "hello world!"를 10줄 써 넣기
f = open("./hello.txt", "w")
for _ in range(10): f.write("Hello World! \n")
f.close() |
- append 모드로 열어서 "hello python!"을 10줄 추가
f = open("./hello.txt", "a")
for _ in range(10): f.write("Hello Python! \n")
f.close |
- 파일을 읽어 온 뒤에 파일 내용에 hello world를 20번, hello python을 10번 출력 해보기
f = open("./hello.txt", "r")
for _ in range(10): f.write(f.readline())
f.seek(0) print(f.read())
f.close |
csv파일 변환
- key값이 최소 3개 이상인 dictionary를 최소 3개 포함한 리스트를 csv파일로 만들어서 저장하는 함수를 만들기
중요 |
import pprint
values = [{ "a":"1", "b":"2", "c":"3" } for _ in range(3)]
pprint.print(value)
def to_csv(value): keys = [] for el in value[0]: keys.append(el)
results = [] for d in value: result = [] for el in d.values(): result.append(el) results.append(result)
content = ', '.join(keys) # , 로 각 문자가 연결 됨 for result in results: content += ', '.join(result) + '\n' f = open('.csv_file.txt', 'w') f.write(content) f.close() if not f.closed: print("파일이 종료되지 않았습니다.")
to_csv(values) |
- 저장한 csv 파일을 불러와서 다시 dictionary로 변환하는 함수 만들기
with 사용
with는 자동으로 들여쓰기 안에서만 사용하므로 따로 닫을 필요가 없다. 들여쓰기 끝나면 자동으로 닫아 준다.
with open('path', 'mode') as f: # f라는 변수에 넣어서 파일 사용 f.write("Hello.") |
- 참고
python은 모든 것이 객체.
dir() 을 이용해서 f = open("./text.txt", 'w') 를 열어보면 아래와 같다.
즉, with 메서드는 __exit__를 갖고 있다는 것.
module
- 모듈 : 프로그램(기능)의 모음
(ex) from ** import ***
import ***
# file.py에 저장
def add_all(*args): return sum(args)
>>> from file import file or >>> import file >>> file.add_all(1, 2, 3, 4, 5) |
__name__ : 파일명
python으로 실행된 파일은 __name__ == "__main__" 이다.
if __name__=="__main__": main() print("Start point!") |
파이썬 파일을 모듈로써 호출하지 않을 때 특정 코드 실행시키기
dir()
객체에 어떤 기능들, 값들이 있는지 알 수 있다.
(ex)
>>> dir(1)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
'Programming > Django' 카테고리의 다른 글
PYTHON & DJANGO 온라인 강의 수업노트 DAY8 (0) | 2018.04.18 |
---|---|
PYTHON & DJANGO 온라인 강의 수업노트 DAY7 (0) | 2018.04.18 |
PYTHON & DJANGO 온라인 강의 수업노트 DAY5 (0) | 2018.04.18 |
PYTHON & DJANGO 온라인 강의 수업노트 DAY4 (0) | 2018.04.18 |
PYTHON & DJANGO 온라인 강의 수업노트 DAY3 (0) | 2018.04.18 |