Python: brug kopifilkommando - hvordan det fungerer
Denne Python-guide viser, hvordan du kan bruge kopifilen-kommandoen i Python til at kopiere en fil. Ved hjælp af et simpelt eksempel kan du nemt gøre det selv.
Brug kopifilkommando i Python
Med kommandoen til kopifil i Python kan filer let kopieres:
- Tilføj kommandoen "from shutil import copyfile" (uden anførselstegn) til begyndelsen af din kode, så du kan bruge kommandoen bagefter.
- Kommandosyntaxen er "copyfile (src, dst)". Så bare indsæt de værdier, du har brug for til dit program.
- Et eksempel på dette ville være: "copyfile ('/ src / dir / file.txt', '/dst/dir/file_with_new_name.txt')".
- Som du kan se, kan du ikke kun kopiere din fil, men også ændre navnet på filen i målmappen.
- Tip: Du kan også bruge "/ dst / dir /" i stedet for "/dst/dir/file_with_new_name.txt" i kommandoen. Dette kopierer filen med det originale filnavn og gemmer den i målmappen.
Python: Kopier fil - andre indstillinger
For at kopiere en fil i Python introducerede vi shutil-metoden i det foregående afsnit. Du kan dog også kopiere en fil uden shutil-modulet:
- Først og fremmest skal du tilføje kommandoen "import os" øverst på din kode.
- Under Windows kan du nu kopiere en fil med kommandoen "os.system ('kopi D: /test.txt F: /')".
- Med Linux skal du bruge kommandoen "os.system ('cp /home/user/test.txt / tmp /')".
- I begge tilfælde udføres en kopikommando. Du kan også skrive andre kommandoer mellem parenteserne, der derefter udføres i terminalen eller i CMD.
Flere tip om Python i vores CHIP-guider
Tip: Du kan finde yderligere programmeringsvejledninger på vores emne-side om programmeringssprog for Python. For eksempel vil vi vise dig, hvordan du opretter og bruger arrays i Python.