Python으로 파일 덮어 쓰기
이 튜토리얼은 Python에서 파일을 덮어 쓰는 다양한 방법을 보여줍니다. 이미 저장된 텍스트를 삭제하여 새 텍스트를 작성하는 방법과 파일의 데이터를 먼저 읽고 일부 작업과 변경 사항을 적용한 다음 이전 데이터에 덮어 쓰는 방법을 살펴 보겠습니다.
open()함수를 사용하여 Python에서 파일 덮어 쓰기
open(file, mode)함수는file(경로 형 객체)을 입력으로 사용하고 파일 객체를 출력으로 반환합니다. file입력은 문자열 또는 바이트 객체 일 수 있으며 파일 경로를 포함합니다. mode는 파일을 열려는 모드입니다. 읽기 모드의 경우r, 쓰기 모드의 경우w, 추가 모드의 경우a등이 될 수 있습니다.
파일을 덮어 쓰고 일부 새 데이터를 파일에 쓰려면w모드에서 파일을 열면 파일에서 이전 데이터가 삭제됩니다.
예제 코드 :
with open("myFolder/myfile.txt", "w") as myfile:
myfile.write(newData)
먼저 파일에 저장된 데이터를 읽은 다음 파일을 덮어 쓰려면 먼저 파일을 읽기 모드로 열고 데이터를 읽은 다음 파일을 덮어 쓸 수 있습니다.
예제 코드:
with open("myFolder/myfile.txt", "r") as myfile:
data = myfilef.read()
with open("myFolder/myfile.txt", "w") as myfile:
myfile.write(newData)
file.truncate()메서드를 사용하여 Python에서 파일 덮어 쓰기
먼저 파일 데이터를 읽은 다음 덮어 쓰기를 원하기 때문에file.truncate()메소드를 사용하여 그렇게 할 수 있습니다.
먼저open()메서드를 사용하여 읽기 모드에서 파일을 열고 파일 데이터를 읽고file.seek()메서드를 사용하여 파일의 시작 부분을 찾습니다, 새 데이터를 쓰고file.truncate()메서드를 사용하여 이전 데이터를 자릅니다.
아래 예제 코드는file.seek()및file.truncate()메소드를 사용하여 파일을 덮어 쓰는 방법을 보여줍니다.
with open("myFolder/myfile.txt", "r+") as myfile:
data = myfile.read()
myfile.seek(0)
myfile.write("newData")
myfile.truncate()
Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.
LinkedIn