#!/usr/bin/env python # coding: utf-8 # # Chapter 21 File Input and Output # # # In[1]: # 01 백문이 불여일견 my_list = [i**2 for i in range(1,11)] # Generates a list of squares of the numbers 1 - 10 f = open("output.txt", "w") for item in my_list: f.write(str(item) + "\n") f.close() # # check output.txt # In[2]: # 02 open() 함수 my_file = open("output.txt", "r+") # In[3]: # 03 쓰기(Writing) my_list = [i**2 for i in range(1,11)] my_file = open("output.txt", "r+") # Add your code below! for e in my_list: my_file.write(str(e) + "\n") my_file.close() # In[4]: # 04 읽기(Reading) my_file = open("output.txt", "r") print (my_file.read()) my_file.close() # In[5]: # 05 한 줄씩 읽어나가기 my_file = open("output.txt", "r") print (my_file.readline()) print (my_file.readline()) print (my_file.readline()) my_file.close() # In[6]: # 06 데이터 버퍼링(Data Buffering) # Open the file for reading read_file = open("output.txt", "r") # Use a second file handler to open the file for writing write_file = open("text.txt", "w") # Write to the file write_file.write("Not closing files is VERY BAD.") write_file.close() # Try to read from the file print (read_file.read()) read_file.close() # In[7]: # 07 'with'와 'as' 키워드 with open("text.txt", "w") as textfile: textfile.write("Success!") # In[8]: # 08 혼자 힘으로 해보세요 with open("text.txt", "w") as my_file: my_file.write("HOHOHOHOHO~~~~!!") # In[9]: # 09 제대로 닫혔나요? with open("text.txt", "w") as my_file: my_file.write("HOHOHOHOHO~~~~!!") print (my_file.closed) if my_file.closed == False: my_file.close() print (my_file.closed)