Python: usa il comando copia file - come funziona
Questa guida di Python mostra come utilizzare il comando copia file in Python per copiare un file. Usando un semplice esempio, puoi farlo facilmente da solo.
Usa il comando copia file in Python
Con il comando copia file in Python, i file possono essere facilmente copiati:
- Aggiungi il comando "from shutil import copyfile" (senza virgolette) all'inizio del codice in modo da poter utilizzare il comando in seguito.
- La sintassi del comando è "copyfile (src, dst)". Quindi inserisci solo i valori necessari per il tuo programma.
- Un esempio di questo sarebbe: "copyfile ('/ src / dir / file.txt', '/dst/dir/file_with_new_name.txt')".
- Come puoi vedere, puoi non solo copiare il tuo file, ma anche cambiare il nome del file nella directory di destinazione.
- Suggerimento: puoi anche usare "/ dst / dir /" invece di "/dst/dir/Datei_mit_neuem_Namen.txt" nel comando. Questo copia il file con il nome del file originale e lo memorizza nella directory di destinazione.
Python: copia il file - altre opzioni
Per copiare un file in Python, abbiamo introdotto il metodo shutil nel paragrafo precedente. Tuttavia, puoi anche copiare un file senza il modulo shutil:
- Prima di tutto devi aggiungere il comando "import os" nella parte superiore del codice.
- In Windows ora puoi copiare un file con il comando "os.system ('copy D: /test.txt F: /')".
- Con Linux devi usare il comando "os.system ('cp /home/user/test.txt / tmp /')".
- In entrambi i casi, viene eseguito un comando di copia. È anche possibile scrivere altri comandi tra parentesi, che vengono quindi eseguiti nel terminale o in CMD.
Ulteriori suggerimenti su Python nelle nostre guide CHIP
Suggerimento: puoi trovare ulteriori tutorial di programmazione sulla nostra pagina degli argomenti del linguaggio di programmazione Python. Ad esempio, ti mostreremo come creare e utilizzare le matrici in Python.