Directories in Python
Last updated Aug 13, 2021Renaming and removing file
Rename file- using rename() used to rename the file, need the name of the current file name and the renamed name.
SYNTAX:-
os.rename(current_file_name, new_file_name)
|
Let's take an example for the same:-
import os os.rename( "code.txt", "code1.txt" ) |
Removing file- using remove() to delete a file.
SYNTAX:-
os.remove(file_name) |
You can refer to the following example for removing a file:-
import os os.remove("text2.txt") |
Directories in Python
A directory or folder is a collection of files. Python has the os module that provides us with several useful methods to work with directories.
- The getcwd() method- get the current working directory in form of a string
Example:-
import os
os.getcwd()
|
- The mkdir() method – making a new directory if the path is not set the directory will be made in the current directory
Example:-
os.mkdir('python')
|
- The rename() method- The rename() method can rename a directory or a file. This method needs the old name of the directory and the new renamed name.
Example:-
os.listdir() >>['old name'] os.rename('oldname','newname') os.listdir() >>['newname'] |
- The rmdir() method- A file can be removed (deleted) using the rmdir() method.
Example:-
os. rmdir ('old.txt')
|
- The chdir() Method- change the current directory
Example:-
os.chdir("newdir")
|
These methods of directories are used in python for solving os related problems and it helps us to work well with python directories.
Article Contributed By :
|
|
|
|
66 Views |