メインコンテンツまでスキップ

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

Pythonでファイルをコピーする手順について、ステップバイステップのチュートリアルをご紹介します:

ステップ1:必要なモジュールをインポートする

Pythonでファイルをコピーするには、shutilモジュールをインポートする必要があります。このモジュールはファイル操作のための高レベルなインターフェースを提供しています。

import shutil

ステップ2:ソースファイルとコピー先を指定する

次に、コピーしたいソースファイルのパスと、コピー先のパスを指定します。完全なファイルパスを含めるようにしてください。

source_file = 'path/to/source_file.txt'
destination = 'path/to/destination_folder'

ステップ3:shutil.copy()を使ってファイルをコピーする

次に、shutil.copy()関数を使ってファイルをコピーします。この関数には2つの引数、つまりソースファイルとコピー先フォルダが必要です。

shutil.copy(source_file, destination)

ステップ4:例外処理を行う

ファイルのコピー中に発生する可能性のある例外を適切に処理することが重要です。最も一般的な例外はshutil.Errorで、ソースとコピー先が同じファイルである場合やパーミッションの問題がある場合に発生します。

try:
shutil.copy(source_file, destination)
except shutil.Error as e:
print(f"エラー:{e}")
except Exception as e:
print(f"エラー:{e}")

ステップ5:ファイルコピーの確認

ファイルが正常にコピーされたかどうかを確認するために、osモジュールのos.path.exists()関数を使用してコピー先ファイルが存在するかどうかを確認できます。

import os

destination_file = os.path.join(destination, os.path.basename(source_file))

if os.path.exists(destination_file):
print("ファイルが正常にコピーされました!")
else:
print("ファイルのコピーに失敗しました!")

ステップ6:完全なコード例

以下はPythonでファイルをコピーするための完全なコード例です:

import shutil
import os

source_file = 'path/to/source_file.txt'
destination = 'path/to/destination_folder'

try:
shutil.copy(source_file, destination)
except shutil.Error as e:
print(f"エラー:{e}")
except Exception as e:
print(f"エラー:{e}")

destination_file = os.path.join(destination, os.path.basename(source_file))

if os.path.exists(destination_file):
print("ファイルが正常にコピーされました!")
else:
print("ファイルのコピーに失敗しました!")

以上です!Pythonのshutilモジュールを使用してファイルをコピーすることに成功しました。