산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> python

Python에서 파일 복사:shutil.copy(), shutil.copystat() 메서드

파이썬 복사 파일 방법

Python은 운영 체제 셸 유틸리티를 사용하여 파일을 쉽게 복사할 수 있는 내장 기능을 제공합니다.

다음 명령은 파일 복사에 사용됩니다.

shutil.copy(src,dst)

다음 명령은 메타데이터 정보가 있는 파일을 복사하는 데 사용됩니다.

shutil.copystat(src,dst)

파이썬에서 파일을 복사하는 방법

다음은 shutil copy() 메서드를 사용하여 Python에서 파일을 복사하는 단계입니다.

1단계) 현재 디렉토리에서 원본 경로 캡처
파일을 복사하기 전에 현재 디렉토리에서 원본 파일의 경로를 가져와야 합니다. 코드에서 –

  1. 변수 선언
  2. 변수에 분할 기능 적용

코드 설명

2단계) shutil 모듈을 사용하여 기존 파일의 복사본을 만듭니다.
우리는 Shutil 모듈을 사용하여 기존 파일의 복사본을 만듭니다. 여기에서 기존 파일 "guru99.txt"의 복사본을 만들었습니다.

코드 설명

3단계) 파일, 파일 권한 및 기타 정보와 관련된 메타 데이터 복사
복사 기능은 파일의 내용만 복사하고 다른 정보는 복사하지 않습니다. 메타데이터를 복사하려면 "copystat을(를) 사용해야 하는 파일, 파일 권한 및 기타 정보와 관련된 " 기능. 이 코드를 실행하기 전에 "guru99.text.bak" 복사 파일을 삭제해야 합니다.

파일을 삭제하고 프로그램을 실행하면 .txt 파일의 복사본이 생성되지만 이번에는 파일 권한, 수정 시간 및 메타데이터 정보와 같은 모든 정보가 포함됩니다. . OS 셸로 이동하여 정보를 확인할 수 있습니다.

코드는 다음과 같습니다.

import os
import shutil
from os import path

def main():
    # make a duplicate of an existing file
	if path.exists("guru99.txt"):
    # get the path to the file in the current directory
        src = path.realpath("guru99.txt");
    
	#seperate the path from the filter
	head, tail = path.split(src)
	print("path:" +head)
	print("file:" +tail)
	
	#let's make a backup copy by appending "bak" to the name
	dst = src+".bak"
	# nowuse the shell to make a copy of the file
	shutil.copy(src, dst)
	
	#copy over the permissions,modification
	shutil.copystat(src,dst)
	
if __name__=="__main__":
	main()

4단계) 정보 가져오기
마지막으로 수정한 텍스트 파일에 대한 정보를 가져올 수 있습니다.

코드는 다음과 같습니다.

#
# Example file for working with o.s path module


import os
from os import path
import datetime
from datetime import date, time, timedelta
import time

def main():


    # Get the modification time
    t = time.ctime(path.getmtime("guru99.txt.bak"))
    print(t)
    print(datetime.datetime.fromtimestamp(path.getmtime("guru99.txt.bak")))


if __name__ == "__main__":
    main()

요약


python

  1. 파이썬 데이터 유형
  2. 파이썬 연산자
  3. 파이썬 통과 문
  4. 파이썬 함수 인수
  5. 파이썬 사전
  6. 파이썬 파일 I/O
  7. 파이썬 문자열 길이 | len() 메서드 예제
  8. 예제가 있는 Python 문자열 find() 메서드
  9. Python 파일 존재 여부 확인 | 파이썬에서 디렉토리가 존재하는지 확인하는 방법
  10. Python JSON:인코딩(덤프), 디코딩(로드) 및 JSON 파일 읽기