본문 바로가기
Python(Eng. ver)

20. File I/O in Python

by 곽정우 2024. 3. 20.

1. File Open

파이썬에서 파일을 열려면 open() 함수를 사용합니다. open() 함수는 두 가지 인수를 받습니다.

2. File Write

There are two watys to write coontent to a file

  • write(): Writing a string to the file
  • writelines(): Writehs a list of strings to the file

 

3. Using the With statement

Python's with statement allows user to open a file, perform operations on it, and automatically close the file afterwards

 

4. File Read

There are serveral ways to read the file

  • read(): Returns the entire contents of the file as a string.
  • readline(): Returns one line of the file as a string
  • readlines(): Returns all lines of the file as a list

 

5. Exception Handling in File I/O

When working with files in Python, various errors can occur, such as the file not existing or permission issues. To handle these errors gracefully, user can use try-except blocks.

 

6.  Additional Information

  • Checking if a file exists : Use the os.path.exists() function to check if a file exists.
  • Deletinga file : Use the os.remove() function to delete a file
  • Copying a file: Use the shutil.copyfile() function to copy a file
  • Renaming a file:  Use the  os.rename() function to rename a file

'Python(Eng. ver)' 카테고리의 다른 글

22. Variable type annotation  (0) 2024.03.21
21. Creating a vocabulary book using file input and output  (0) 2024.03.21
19. Python Module  (0) 2024.03.20
18. Python Error Handling  (0) 2024.03.19
17. Special Method  (0) 2024.03.19