Python: bruk kopifilkommando - hvordan det fungerer
Denne Python-guiden viser hvordan du kan bruke kopifil-kommandoen i Python til å kopiere en fil. Ved hjelp av et enkelt eksempel kan du enkelt gjøre det selv.
Bruk kopifilkommando i Python
Med kopifilkommandoen i Python kan filer enkelt kopieres:
- Legg til kommandoen "from shutil import copyfile" (uten anførselstegn) i begynnelsen av koden slik at du kan bruke kommandoen etterpå.
- Kommandosyntaxen er "copyfile (src, dst)". Så det er bare å sette inn verdiene du trenger for programmet ditt.
- Et eksempel på dette vil være: "copyfile ('/ src / dir / file.txt', '/dst/dir/file_with_new_name.txt')".
- Som du kan se, kan du ikke bare kopiere filen, men også endre navnet på filen i målkatalogen.
- Tips: Du kan også bruke "/ dst / dir /" i stedet for "/dst/dir/file_with_new_name.txt" i kommandoen. Dette kopierer filen med det originale filnavnet og lagrer den i målkatalogen.
Python: Kopier fil - andre alternativer
For å kopiere en fil i Python introduserte vi shutil-metoden i forrige avsnitt. Du kan imidlertid også kopiere en fil uten shutil-modulen:
- Først av alt må du legge til kommandoen "import os" øverst på koden.
- Under Windows kan du nå kopiere en fil med kommandoen "os.system ('copy D: /test.txt F: /')".
- Med Linux må du bruke kommandoen "os.system ('cp /home/user/test.txt / tmp /')".
- I begge tilfeller utføres en kopikommando. Du kan også skrive andre kommandoer mellom parentesene, som deretter blir utført i terminalen eller i CMD.
Flere tips om Python i våre CHIP-guider
Tips: Du kan finne ytterligere programmeringsopplæringer på emnesiden vår for Python programmeringsspråk. For eksempel vil vi vise deg hvordan du oppretter og bruker matriser i Python.