IT story

Python에서 텍스트 파일의 파일 내용을 지우는 방법은 무엇입니까?

hot-time 2020. 8. 22. 12:17
반응형

Python에서 텍스트 파일의 파일 내용을 지우는 방법은 무엇입니까?


파이썬에서 지우고 싶은 텍스트 파일이 있습니다. 어떻게하나요?


파이썬에서 :

open('file.txt', 'w').close()

또는 이미 열린 파일이있는 경우 :

f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+

C ++에서 비슷한 것을 사용할 수 있습니다.


완전한 답변이 아닌 온 드라의 답변에 대한 확장

사용하는 경우 truncate()확인 (내 선호하는 방법)을 만든다 커서가 필요한 위치에있다. 읽기를 위해 새 파일이 열리면 open('FILE_NAME','r')커서는 기본적으로 0에 있습니다. 그러나 코드 내에서 파일을 구문 분석 한 경우 파일의 시작 부분을 다시 가리켜 야합니다. 즉, truncate(0)기본적으로 truncate()현재 커서 위치에서 시작하는 파일의 내용을 자릅니다.

간단한 예


"쓰기"모드에서 파일을 열면 파일이 지워 지므로 특별히 쓸 필요가 없습니다.

open("filename", "w").close()

(파일이 자동으로 닫히는 타이밍은 구현에 따라 다를 수 있으므로 닫아야합니다)


파일을 덮어 써야합니다. C ++에서 :

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

사용자 @jamylak의 대체 형식은 다음 open("filename","w").close()과 같습니다.

with open('filename.txt','w'): pass

를 사용할 때 , 특히 파일을 먼저 읽고 있기 때문에 with open("myfile.txt", "r+") as my_file:에서 이상한 0이 생깁니다 myfile.txt. 작동하려면 먼저 my_file파일의 시작 부분에 대한 포인터 my_file.seek(0). 그러면 my_file.truncate()파일을 지울 수 있습니다.


프로그램 내에서 파일 포인터를 null에 할당하면 파일에 대한 참조가 제거됩니다. 파일이 아직 있습니다. 나는 remove()c 기능 stdio.h이 당신이 거기에서 찾고 있는 것이라고 생각합니다 . Python에 대해 잘 모르겠습니다.


보안이 중요하다면 쓰기 위해 파일을 열고 다시 닫는 것만으로는 충분하지 않습니다. 적어도 일부 정보는 여전히 저장 장치에 있으며 예를 들어 디스크 복구 유틸리티를 사용하여 찾을 수 있습니다.

예를 들어 지우려는 파일에 프로덕션 암호가 포함되어 있으며 현재 작업이 완료된 후 즉시 삭제해야한다고 가정합니다.

파일 사용을 마친 후 파일을 0으로 채우면 민감한 정보를 삭제하는 데 도움이됩니다.

최근 프로젝트에서 우리는 작은 텍스트 파일에 잘 작동하는 다음 코드를 사용했습니다. 기존 내용을 0 줄로 덮어 씁니다.

import os

def destroy_password_file(password_filename):
    with open(password_filename) as password_file:
        text = password_file.read()
    lentext = len(text)
    zero_fill_line_length = 40
    zero_fill = ['0' * zero_fill_line_length
                      for _
                      in range(lentext // zero_fill_line_length + 1)]
    zero_fill = os.linesep.join(zero_fill)
    with open(password_filename, 'w') as password_file:
        password_file.write(zero_fill)

제로 채우기는 보안을 보장하지 않습니다. 정말 걱정된다면 제로 채우기를 하고 File Shredder 또는 CCleaner 와 같은 전문 유틸리티를 사용 하여 드라이브의 '빈'공간을 정리하는 것이 가장 좋습니다 .


끝 부분을 지울 필요가 없으면 파일에서 "지우기"를 할 수 없습니다. "빈"값을 덮어 쓰는 내용이 있거나 파일에서 관심있는 부분을 읽고 다른 파일에 쓰십시오.


텍스트 파일은 순차적이므로 직접 데이터를 지울 수 없습니다. 옵션은 다음과 같습니다.

  • The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
  • You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
  • Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.

Look at the seek/truncate function/method to implement any of the ideas above. Both Python and C have those functions.

참고URL : https://stackoverflow.com/questions/2769061/how-to-erase-the-file-contents-of-text-file-in-python

반응형