Python では、さまざまなアプローチに従ってファイル サイズを取得できます。ファイル サイズを監視する場合、またはファイル サイズに従ってディレクトリ内のファイルを並べ替える場合には、Python でファイル サイズを取得することが重要です。
方法 1: 使用する サイズを取得する の方程式 OSパス モジュール
この関数はファイル パスを引数として受け取り、ファイル サイズ (バイト) を返します。
カトリーナ・カイフ
例:
Python3
# 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モジュールの機能
この関数は、ファイル パスを引数 (文字列またはファイル オブジェクト) として受け取り、入力として指定されたファイル パスに関する統計の詳細を返します。
例:
Python3
# 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: ファイルオブジェクトの使用
ファイル サイズを取得するには、次の手順に従います。
- 使用 開ける ファイルを開き、返されたオブジェクトを変数に格納する関数。ファイルを開くと、カーソルがファイルの先頭を指します。
- ファイルオブジェクトには 求める カーソルを目的の位置に設定するために使用されるメソッド。開始位置と終了位置の 2 つの引数を受け入れます。ファイルの終了位置にカーソルを設定するには、次の方法を使用します。 os.SEEK_END。
- ファイルオブジェクトには 教えて このメソッドは、カーソルが移動したバイト数に相当する現在のカーソル位置を取得するために使用できます。したがって、このメソッドは実際にはファイルのサイズをバイト単位で返します。
例:
Python3
文字列の連結
# 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: パスライブラリモジュールの使用
Path オブジェクトの stat() メソッドは、ファイルの st_mode、st_dev などのプロパティを返します。また、stat メソッドの st_size 属性はファイル サイズをバイト単位で示します。
C言語による行列プログラム
例:
Python3
# approach 4> # using pathlib module> from> pathlib> import> Path> # open file> Path(r> 'd:/file.webp'plain'>).stat()>> => 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>