다른 언어와 마찬가지로 Python은 파일 읽기, 쓰기 또는 액세스를 위한 몇 가지 내장 기능을 제공합니다. Python은 주로 두 가지 유형의 파일을 처리할 수 있습니다. 일반 텍스트 파일과 바이너리 파일입니다.
텍스트 파일의 경우 각 줄은 특수 문자 '\n'으로 종료됩니다(EOL 또는 줄 끝이라고 함). 바이너리 파일의 경우 줄 끝 문자가 없습니다. 내용을 비트스트림으로 변환하여 데이터를 저장합니다.
이 섹션에서는 텍스트 파일에 대해 설명합니다.
파일 액세스 모드
| Sr.No | 모드 및 설명 |
|---|---|
| 1 | r 읽기 전용 모드입니다. 읽을 수 있도록 텍스트 파일을 엽니다. 파일이 없으면 I/O Error를 발생시킵니다. |
| 2 | r+ 읽기 및 쓰기용 모드입니다. 파일이 없으면 I/O 오류가 발생합니다. |
| 3 | ㅁ 쓰기 전용 작업입니다. 파일이 없으면 먼저 파일을 생성한 다음 쓰기를 시작하고, 파일이 있으면 해당 파일의 내용을 제거하고 처음부터 쓰기를 시작합니다. |
| 4 | w+ 쓰기 및 읽기 모드입니다. 파일이 없으면 파일을 생성할 수 있고 파일이 있으면 데이터를 덮어씁니다. |
| 5 | 아 추가 모드입니다. 따라서 파일 끝에 데이터를 씁니다. |
| 6 | a+ 추가 및 읽기 모드. 데이터를 읽을 뿐만 아니라 데이터를 추가할 수 있습니다. |
이제 writelines() 및 write() 메소드를 사용하여 파일을 작성하는 방법을 살펴보십시오.
예시 코드
#Create an empty file and write some lines
line1 = 'This is first line. \n'
lines = ['This is another line to store into file.\n',
'The Third Line for the file.\n',
'Another line... !@#$%^&*()_+.\n',
'End Line']
#open the file as write mode
my_file = open('file_read_write.txt', 'w')
my_file.write(line1)
my_file.writelines(lines) #Write multiple lines
my_file.close()
print('Writing Complete')
출력
Writing Complete
줄을 작성한 후 파일에 몇 줄을 추가합니다.
예시 코드
#program to append some lines
line1 = '\n\nThis is a new line. This line will be appended. \n'
#open the file as append mode
my_file = open('file_read_write.txt', 'a')
my_file.write(line1)
my_file.close()
print('Appending Done')
출력
Appending Done
마지막으로 read() 및 readline() 메서드에서 파일 내용을 읽는 방법을 살펴보겠습니다. 처음 'n'자를 얻기 위해 정수 'n'을 제공할 수 있습니다.
예시 코드
#program to read from file
#open the file as read mode
my_file = open('file_read_write.txt', 'r')
print('Show the full content:')
print(my_file.read())
#Show first two lines
my_file.seek(0)
print('First two lines:')
print(my_file.readline(), end = '')
print(my_file.readline(), end = '')
#Show upto 25 characters
my_file.seek(0)
print('\n\nFirst 25 characters:')
print(my_file.read(25), end = '')
my_file.close()
출력
Show the full content: This is first line. This is another line to store into file. The Third Line for the file. Another line... !@#$%^&*()_+. End Line This is a new line. This line will be appended. First two lines: This is first line. This is another line to store into file. First 25 characters: This is first line. This