Blog Content

    티스토리 뷰

    PYTHON & DJANGO 온라인 강의 수업노트 DAY6

    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()

     

     

     

    연습

    파일 만들고 읽어오기

     

    1. 파일을 만들어서 "hello world!" 10 넣기

    f = open("./hello.txt", "w")

     

    for _ in range(10):

    f.write("Hello World! \n")

     

    f.close()

     

    1. append 모드로 열어서 "hello python!" 10 추가

    f = open("./hello.txt", "a")

     

    for _ in range(10):

    f.write("Hello Python! \n")

     

    f.close

     

    1. 파일을 읽어 뒤에 파일 내용에 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파일 변환

    1. 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)

     

     

    1. 저장한 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']


    Comments