Python: ใช้คำสั่ง copy file - วิธีการทำงาน
คู่มือ Python นี้แสดงวิธีการใช้คำสั่งคัดลอกไฟล์ใน Python เพื่อคัดลอกไฟล์ โดยใช้ตัวอย่างง่ายๆคุณสามารถทำมันเองได้อย่างง่ายดาย
ใช้คำสั่งคัดลอกไฟล์ใน Python
ด้วยคำสั่ง copy file ใน Python สามารถคัดลอกไฟล์ได้อย่างง่ายดาย:
- เพิ่มคำสั่ง "จาก shutil import copyfile" (โดยไม่ใส่เครื่องหมายอัญประกาศ) ไปยังจุดเริ่มต้นของรหัสของคุณเพื่อให้คุณสามารถใช้คำสั่งได้ในภายหลัง
- ไวยากรณ์คำสั่งคือ "copyfile (src, dst)" ดังนั้นเพียงแค่ใส่ค่าที่คุณต้องการสำหรับโปรแกรมของคุณ
- ตัวอย่างนี้จะเป็น: "copyfile ('/ src / dir / file.txt', '/dst/dir/file_with_new_name.txt')"
- อย่างที่คุณเห็นคุณไม่เพียง แต่สามารถคัดลอกไฟล์ของคุณ แต่ยังเปลี่ยนชื่อของไฟล์ในไดเรกทอรีเป้าหมาย
- เคล็ดลับ: คุณสามารถใช้ "/ dst / dir /" แทน "/dst/dir/file_with_new_name.txt" ในคำสั่ง สิ่งนี้จะคัดลอกไฟล์ด้วยชื่อไฟล์ต้นฉบับและเก็บไว้ในไดเรกทอรีเป้าหมาย
Python: คัดลอกไฟล์ - ตัวเลือกอื่น ๆ
ในการคัดลอกไฟล์ใน Python เราแนะนำวิธีการปิดระบบในย่อหน้าก่อนหน้า อย่างไรก็ตามคุณสามารถคัดลอกไฟล์โดยไม่ต้องปิดโมดูล:
- ก่อนอื่นคุณต้องเพิ่มคำสั่ง "import os" ที่ด้านบนของรหัสของคุณ
- ใน Windows คุณสามารถคัดลอกไฟล์ด้วยคำสั่ง "os.system ('copy D: /test.txt F: /')"
- ด้วย Linux คุณต้องใช้คำสั่ง "os.system ('cp /home/user/test.txt / tmp /')"
- ในทั้งสองกรณีคำสั่ง copy จะถูกดำเนินการ คุณยังสามารถเขียนคำสั่งอื่น ๆ ระหว่างวงเล็บซึ่งจะดำเนินการใน terminal หรือใน CMD
เคล็ดลับเพิ่มเติมเกี่ยวกับ Python ในคู่มือ CHIP ของเรา
เคล็ดลับ: คุณสามารถค้นหาบทช่วยสอนการเขียนโปรแกรมเพิ่มเติมได้ในหน้าหัวข้อภาษาการเขียนโปรแกรม Python ของเรา ตัวอย่างเช่นเราจะแสดงวิธีสร้างและใช้อาร์เรย์ใน Python