Python: gunakan perintah salin file - cara kerjanya
Panduan Python ini menunjukkan bagaimana Anda dapat menggunakan perintah salin file dalam Python untuk menyalin file. Dengan menggunakan contoh sederhana, Anda dapat dengan mudah melakukannya sendiri.
Gunakan perintah salin file dalam Python
Dengan perintah menyalin file dengan Python, file dapat dengan mudah disalin:
- Tambahkan perintah "from shutil import copyfile" (tanpa tanda kutip) ke awal kode Anda sehingga Anda dapat menggunakan perintah sesudahnya.
- Sintaks perintahnya adalah "copyfile (src, dst)". Jadi cukup masukkan nilai yang Anda butuhkan untuk program Anda.
- Contohnya adalah: "copyfile ('/ src / dir / file.txt', '/dst/dir/file_with_new_name.txt')".
- Seperti yang Anda lihat, Anda tidak hanya dapat menyalin file Anda, tetapi juga mengubah nama file di direktori target.
- Kiat: Anda juga dapat menggunakan "/ dst / dir /" daripada "/dst/dir/file_with_new_name.txt" dalam perintah. Ini menyalin file dengan nama file asli dan menyimpannya di direktori target.
Python: Salin file - opsi lain
Untuk menyalin file dengan Python, kami memperkenalkan metode shutil pada paragraf sebelumnya. Namun, Anda juga dapat menyalin file tanpa modul shutil:
- Pertama-tama Anda harus menambahkan perintah "import os" ke bagian atas kode Anda.
- Di Windows Anda sekarang dapat menyalin file dengan perintah "os.system ('copy D: /test.txt F: /')".
- Dengan Linux Anda harus menggunakan perintah "os.system ('cp /home/user/test.txt / tmp /')".
- Dalam kedua kasus, perintah salin dijalankan. Anda juga dapat menulis perintah lain di antara tanda kurung, yang kemudian dieksekusi di terminal atau di CMD.
Lebih banyak tips tentang Python di panduan CHIP kami
Tip: Anda dapat menemukan tutorial pemrograman lebih lanjut di halaman topik bahasa pemrograman Python kami. Misalnya, kami akan menunjukkan cara membuat dan menggunakan array dengan Python.