工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python でのファイルのコピー:shutil.copy()、shutil.copystat() メソッド

Python コピー ファイル メソッド

Python には、オペレーティング システム シェル ユーティリティを使用してファイルを簡単にコピーするための組み込み関数が用意されています。

次のコマンドは、ファイルをコピーするために使用されます

shutil.copy(src,dst)

次のコマンドは、メタデータ情報を含むファイルをコピーするために使用されます

shutil.copystat(src,dst)

Python でファイルをコピーする方法

shutil copy() メソッドを使用して Python でファイルをコピーする手順は次のとおりです:

ステップ 1) 現在のディレクトリ内の元のパスを取得する
ファイルをコピーする前に、現在のディレクトリ内の元のファイルへのパスを取得する必要があります。コード内 –

<オール>
  • 変数の宣言
  • 変数に分割関数を適用する
  • コードの説明

    ステップ 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. Python データ型
    2. Python 演算子
    3. Python pass ステートメント
    4. Python 関数の引数
    5. Python 辞書
    6. Python ファイル I/O
    7. Python 文字列の長さ | len() メソッドの例
    8. Python String find() メソッドと例
    9. Python ファイルが存在するかどうかを確認します。 Python でディレクトリが存在するかどうかを確認する方法
    10. Python JSON:JSON ファイルのエンコード (ダンプ)、デコード (ロード)、読み取り
    11. Python - ファイル I/O