Python:ファイルのコピーコマンドを使用する-仕組み
このPythonガイドは、Pythonでcopy fileコマンドを使用してファイルをコピーする方法を示しています。 簡単な例を使用すると、自分で簡単に実行できます。
Pythonでファイルのコピーコマンドを使用する
Pythonのファイルのコピーコマンドを使用すると、ファイルを簡単にコピーできます。
- 「from shutil import copyfile」コマンドを(引用符なしで)コードの先頭に追加して、後でコマンドを使用できるようにします。
- コマンド構文は「copyfile(src、dst)」です。 したがって、プログラムに必要な値を挿入するだけです。
- この例は、「copyfile( '/ src / dir / file.txt'、 '/ dst / dir / file_with_new_name.txt')」です。
- ご覧のとおり、ファイルをコピーするだけでなく、ターゲットディレクトリ内のファイル名を変更することもできます。
- ヒント:コマンドで「/dst/dir/file_with_new_name.txt」の代わりに「/ dst / dir /」を使用することもできます。 これにより、元のファイル名でファイルがコピーされ、ターゲットディレクトリに保存されます。
Python:ファイルのコピー-その他のオプション
Pythonでファイルをコピーするために、前の段落でshutilメソッドを導入しました。 ただし、shutilモジュールなしでファイルをコピーすることもできます。
- まず最初に、コマンド「import os」をコードの先頭に追加する必要があります。
- Windowsでは、コマンド「os.system( 'copy D:/test.txt F:/')」でファイルをコピーできるようになりました。
- Linuxでは、コマンド「os.system( 'cp /home/user/test.txt / tmp /')」を使用する必要があります。
- どちらの場合も、コピーコマンドが実行されます。 また、角括弧の間に他のコマンドを記述して、端末またはCMDで実行することもできます。
CHIPガイドのPythonに関するその他のヒント
ヒント:Pythonプログラミング言語のトピックページで、さらにプログラミングチュートリアルを見つけることができます。 たとえば、Pythonで配列を作成して使用する方法を示します。