logo

Python에서 파일 크기를 얻는 방법은 무엇입니까?

Python에서 파일 크기를 얻으려면 다양한 접근 방식을 따를 수 있습니다. 파일 크기를 모니터링하거나 파일 크기에 따라 디렉터리의 파일을 주문하는 경우 Python에서 파일 크기를 가져오는 것이 중요합니다.

방법 1: 사용 게사이즈 기능 OS.경로 기준 치수



이 함수는 파일 경로를 인수로 사용하고 파일 크기(바이트)를 반환합니다.

예:

파이썬3






자바의 문자열 함수



# approach 1> # using getsize function os.path module> import> os> file_size>=> os.path.getsize(>'d:/file.webp'plain'>)> print>(>'File Size is :'>, file_size,>'bytes'>)>

>

>

산출:

File Size is : 218 bytes>

방법 2: 사용 통계 OS 모듈의 기능

이 함수는 파일 경로를 인수(문자열 또는 파일 객체)로 사용하고 입력으로 제공된 파일 경로에 대한 통계 세부 정보를 반환합니다.

예:

자바가 현재 날짜를 가져오는 중

파이썬3




# approach 2> # using stat function of os module> import> os> file_size>=> os.stat(>'d:/file.webp'plain'>)> print>(>'Size of file :'>, file_size.st_size,>'bytes'>)>

>

>

산출:

Size of file : 218 bytes>

방법 3: 파일 객체 사용

파일 크기를 얻으려면 다음 단계를 따르십시오 –

  1. 사용 열려 있는 파일을 열고 반환된 객체를 변수에 저장하는 함수입니다. 파일이 열리면 커서는 파일의 시작 부분을 가리킵니다.
  2. 파일 객체에는 구하다 커서를 원하는 위치로 설정하는 데 사용되는 메서드입니다. 시작 위치와 끝 위치라는 2개의 인수를 허용합니다. 파일 사용 방법의 끝 위치에 커서를 설정하려면 os.SEEK_END.
  3. 파일 객체에는 말하다 커서가 이동한 바이트 수에 해당하는 현재 커서 위치를 가져오는 데 사용할 수 있는 메서드입니다. 따라서 이 메서드는 실제로 파일 크기를 바이트 단위로 반환합니다.

예:

파이썬3

리눅스 실행 cmd


산제이 더트와



# approach 3> # using file object> # open file> file> => open>(>'d:/file.webp'plain'>)> # get the cursor positioned at end> file>.seek(>0>, os.SEEK_END)> # get the current position of cursor> # this will be equivalent to size of file> print>(>'Size of file is :'>,>file>.tell(),>'bytes'>)>

>

>

산출:

Size of file is : 218 bytes>

방법 4: Pathlib 모듈 사용

Path 객체의 stat() 메서드는 파일의 st_mode, st_dev 등 속성을 반환합니다. 그리고 stat 메소드의 st_size 속성은 파일 크기를 바이트 단위로 제공합니다.

예:

파이썬3


자바의 문자열 길이



# approach 4> # using pathlib module> from> pathlib>import> Path> # open file> Path(r>'d:/file.webp'plain'>).stat()> # getting file size> file>=>Path(r>'d:/file.webp'plain'>).stat().st_size> # display the size of the file> print>(>'Size of file is :'>,>file>,>'bytes'>)> # this code was contributed by debrc>

>

>

산출:

Size of file is : 218 bytes>