Python-Ref > System interaction > Manipulating files and directories > Moving files around
 
 

<-^^->

Moving files around

How to copy, move or delete files and whole directories.
The os module provides only a few functions to rename and remove files and directories. The following code show what it has to offer.
Expand/Shrink
Prostředí:
.
|-- filesystem2-1.py
|-- something
|   `-- example.py
|-- something_else
`-- test
    `-- test.txt
  1   import os
  2   
  3   # remove a file
  4   os.remove( "test/test.txt")
  5   
  6   # remove an empty directory
  7   os.rmdir( "test")
  8   
  9   # rename a file
 10   os.rename( "filesystem2-1.py", "new_script.py")
Prostředí:
.
|-- new_script.py
|-- something
|   `-- example.py
`-- something_else
Doba běhu: 33.0 ms
The os module does not contain functions for copying files. You have either to open a file for reading, read the content, open the file for writing and write the content there. Of course this is tedious and therefor a new module was created to simplify these matters - shutil.
Expand/Shrink
Prostředí:
.
|-- filesystem2-2.py
|-- something
|   `-- example.py
|-- something_else
`-- test
    `-- test.txt
  1   import shutil
  2   
  3   # copy a file to a directory
  4   shutil.copy( "filesystem2-2.py", "test")
  5   
  6   # copy the whole tree
  7   shutil.copytree( "test", "test2")
  8   
  9   # remove the whole tree
 10   shutil.rmtree( "test")
Prostředí:
.
|-- filesystem2-2.py
|-- something
|   `-- example.py
|-- something_else
`-- test2
    |-- filesystem2-2.py
    `-- test.txt
Doba běhu: 34.5 ms
Directory creation is easily accomplished using the function mkdir.
Expand/Shrink
Prostředí:
.
`-- filesystem2-3.py
  1   import os
  2   
  3   os.mkdir( "example_dir")
  4   os.mkdir( "example_dir/dir2")
  5   f = file( "example_dir/dir2/example.txt", "w")
  6   f.write( "Hello World")
  7   f.close()
Prostředí:
.
|-- example_dir
|   `-- dir2
|       `-- example.txt
`-- filesystem2-3.py
Doba běhu: 28.2 ms