In [1]:
import os

In [4]:


In [7]:
fname = 'foo-bar.txt'
f=open(fname,'w')
os.remove(fname)

In [8]:
os.remove('non-existing-file.txt')


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-8-9daae82f3147> in <module>()
----> 1 os.remove('non-existing-file.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'non-existing-file.txt'

move/rename


In [10]:
fname = 'foo-bar.txt'
f=open(fname,'w')

os.replace(fname,'foo-bar-new.txt')

In [13]:
fname = 'foo-bar.txt'
f=open(fname,'w')

os.replace('non-existing-file.txt','any-other-name.txt')


---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-13-5101b4b27637> in <module>()
      2 f=open(fname,'w')
      3 
----> 4 os.replace('non-existing-file.txt','any-other-name.txt')

FileNotFoundError: [Errno 2] No such file or directory: 'non-existing-file.txt' -> 'any-other-name.txt'

In [15]:
fname = 'foo-bar.txt'
fname2 = 'bar-baz.txt'

f=open(fname,'w')
f2 = open(fname2,'w')

os.replace(fname,fname2)

In [19]:
fname = 'foo-bar.txt'
fname2 = 'foo/'

f=open(fname,'w')
f2 = open(fname2,'w')

os.replace(fname,dst_dir_fd=fname2)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-cea2e01efedf> in <module>()
      4 f=open(fname,'w')
      5 
----> 6 os.replace(fname,dst_dir_fd=fname2)

TypeError: Required argument 'dst' (pos 2) not found

copy


In [20]:
import shutil

In [25]:
fname = 'foo-bar.txt'
fname2 = 'bar-baz.txt'

f=open(fname,'w')

shutil.copy(fname,fname2)


Out[25]:
'bar-baz.txt'

In [30]:
# target path is a dir
fname = 'foo-bar.txt'
fname2 = 'foo/foo-bar.txt'

with open(fname,'w') as f:
    f.write('source-text')
    
# f=open(fname2,'w')

shutil.copy(fname,'foo/')


Out[30]:
'foo/foo-bar.txt'

In [ ]: