떼닝로그

Python for Data Science, AI & Development - Working with Data in Python (1) 본문

Coursera/IBM Data Science

Python for Data Science, AI & Development - Working with Data in Python (1)

떼닝 2024. 1. 18. 07:53

Python for Data Science

Reading & Writing Files with Open

Reading Files with Open

File Object

File1 = open("/resources/data/Example2.txt", "r")

- 위처럼 사용하면 close 진행해줘야 열려 있던 파일 닫힘처리 됨

- 아래처럼 with를 사용하면 자동으로 파일 닫음

with open("Example1.txt", "r") as File1:
	file_stuff = File1.read()
    
    print(file_stuff)

print(File1.closed)
print(file_stuff)

 

- 아래는 open 뒤에 어떤 type로 내용을 읽는지에 따른 차이

- readlines : 한 줄씩 읽으면서 다 읽어냄

- readline : 딱 맨 위 한 줄만 읽음

- readlines(N) : 안 읽은 부분들 중 N개를 읽어옴

 

 

Writing Files with Open

File Object

File1 = open("/resources/data/Example2.txt", "w")

 

- 위에 건 Example2.txt 파일이 없으면 파일부터 우선 만들어줌

- 아래 건 작성 끝난 뒤에 버퍼 닫아줌

- a 사용하면 파일을 처음부터 만드는 것이 아니라, 기존 파일에 작성해줌

- 아래는 한 파일에 있는 내용을 다른 파일에 작성할 때 사용!

 

Practice Quiz

Q. What are the most common modes used when opening a file?

A. (a)ppend, (r)ead, (w)rite

 

Q. What is the data attribute that will return the title of the file?

A. File1.name

 

Q. What is the command that tells Python to begin a new line?

A. \n

 

Q. What attribute is used to input data into a file?

A. File1.write()

Comments