파일을 읽거나 쓰는 동안 액세스 모드는 열린 파일에서 가능한 작업 유형을 제어합니다. 파일이 열린 후 어떻게 사용되는지를 나타냅니다. 이러한 모드는 파일에서 파일 핸들의 위치도 정의합니다. 이러한 액세스 모드의 정의는 다음과 같습니다.
- 추가만('a'): 쓰기 위해 파일을 엽니다. 추가 및 읽기('a+'): 읽고 쓰기 위해 파일을 엽니다.
Python에서 파일을 추가 모드로 열면 핸들이 파일 끝에 위치합니다. 기록되는 데이터는 기존 데이터 뒤에 삽입됩니다.
예시 1: 추가 모드와 쓰기 모드를 설명하는 Python 프로그램입니다.
파이썬3
d 플립플롭
file1>=> open>(>'myfile.txt'>,>'w'>)> L>=> [>'This is Delhi
'>,>'This is Paris
'>,>'This is London'>]> file1.writelines(L)> file1.close()> # Append-adds at last> file1>=> open>(>'myfile.txt'>,>'a'>)># append mode> file1.write(>'Today
'>)> file1.close()> file1>=> open>(>'myfile.txt'>,>'r'>)> print>(>'Output of Readlines after appending'>)> print>(file1.read())> print>()> file1.close()> # Write-Overwrites> file1>=> open>(>'myfile.txt'>,>'w'>)># write mode> file1.write(>'Tomorrow
'>)> file1.close()> file1>=> open>(>'myfile.txt'>,>'r'>)> print>(>'Output of Readlines after writing'>)> print>(file1.read())> print>()> file1.close()> |
>
>
산출:
Output of Readlines after appending This is Delhi This is Paris This is LondonToday Output of Readlines after writing Tomorrow>
예 2: 새 줄에서 데이터 추가
위의 예에서는 파일 처리 , 새로운 줄부터 데이터가 추가되지 않는 것을 볼 수 있습니다. 파일에 줄바꿈 ' ' 문자를 쓰면 됩니다.
파이썬3
# Python program to illustrate> # append from new line> file1>=> open>(>'myfile.txt'>,>'w'>)> L>=> [>'This is Delhi
'>,>'This is Paris
'>,>'This is London'>]> file1.writelines(L)> file1.close()> # Append-adds at last> # append mode> file1>=> open>(>'myfile.txt'>,>'a'>)> # writing newline character> file1.write(>'
'>)> file1.write(>'Today'>)> # without newline character> file1.write(>'Tomorrow'>)> file1>=> open>(>'myfile.txt'>,>'r'>)> print>(>'Output of Readlines after appending'>)> print>(file1.read())> print>()> file1.close()> |
>
>
산출:
Output of Readlines after appending This is Delhi This is Paris This is London TodayTomorrow>
메모: ' '은 2바이트의 특수문자로 처리됩니다.
예시 3: Python에서 With 문 사용
진술 포함 코드를 더욱 깔끔하고 읽기 쉽게 만들기 위해 예외 처리에 사용됩니다. 파일 스트림과 같은 공통 리소스의 관리를 단순화합니다. 위의 구현과 달리 with 문을 사용할 때는 file.close()를 호출할 필요가 없습니다. with 문 자체는 리소스의 적절한 획득 및 해제를 보장합니다.
파이썬3
# Program to show various ways to> # append data to a file using> # with statement> L>=> [>'This is Delhi
'>,>'This is Paris
'>,>'This is London
'>]> # Writing to file> with>open>(>'myfile.txt'>,>'w'>) as file1:> ># Writing data to a file> >file1.write(>'Hello
'>)> >file1.writelines(L)> # Appending to file> with>open>(>'myfile.txt'>,>'a'>) as file1:> >file1.write(>'Today'>)> # Reading from file> with>open>(>'myfile.txt'>,>'r+'>) as file1:> ># Reading form a file> >print>(file1.read())> |
리눅스 명령의 디렉토리
>
>
산출:
Hello This is Delhi This is Paris This is London Today>
메모: with 문에 대해 더 알아보려면 여기를 클릭하세요 .
Shutil 모듈 사용:
이 접근 방식은 quitil.copyfileobj() 메서드를 사용하여 다른 파일(source_file)의 내용을 'file.txt'에 추가합니다. 이는 내용을 먼저 메모리로 읽지 않고도 한 파일의 내용을 다른 파일에 추가하려는 경우 유용할 수 있습니다.
접근하다:
코드는 quitil.copyfileobj() 함수를 사용하여 source_file 객체의 내용을 file.txt라는 새 파일에 복사합니다. with 문은 파일 객체 f를 사용하여 파일을 열고 자동으로 닫는 데 사용됩니다.
시간 복잡도:
quitil.copyfileobj() 함수의 시간 복잡도는 파일의 모든 바이트를 읽고 써야 하기 때문에 복사되는 파일의 크기에 비례합니다. 따라서 코드의 시간 복잡도는 O(n)입니다. 여기서 n은 source_file의 크기입니다.
공간 복잡도:
파일 개체 source_file 및 f에 필요한 것 이상의 추가 메모리를 할당하지 않으므로 코드의 공간 복잡도는 O(1)입니다. shutdown.copyfileobj() 함수는 파일 내용을 덩어리로 복사하므로 전체 파일을 한 번에 메모리에 로드할 필요가 없습니다.
전반적으로 코드는 선형적인 시간 복잡도와 일정한 공간 복잡도를 가지며, 시간 복잡도는 복사되는 파일의 크기에 비례합니다.
파이썬3
자바를 깨다
import> shutil> with>open>(>'file.txt'>,>'a'>) as f:> >shutil.copyfileobj(source_file, f)> |
>
>