What is Directory in Python?
A directory or folder is a collection of files and sub directories. Python has the os module. which provides us with many useful methods to work with directories (and files as well).
Get Current Directory
Use command :
>>>getcwd()
Example:
>>> import module
>>>os.getcwd()
Output:
'C:\\Program Files\\Py...'
Use print() to escape extra backspace.
Example:
>>> print(os.getcwd())
Output:
C:\Program Files\PyScripter
Changing Directory
We can change the current working directory using the chdir() method.
Example:
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
Output:
C:\Python33
List Directories and Files
Use method:
>>>listdir()
Example:
>>> os.listdir()
Output:
['DLLs','Doc','include','Lib','libs',... ]
Create New Directory
Use method
>>> os.mkdir('test')
Renaming a Directory or a File
The rename() method can rename a directory or a file.
>>> os.listdir()
Output:
['test']
>>> os.rename('test','new') #rename "test" into "new"
Removing Directory or File
A file can be removed (deleted) using the remove() method.
rmdir() used to remove empty directory.
Example:
>>> os.remove('file.txt')
Hope you understand the all the concept of file or directory.
If you like Codersarts blog and looking for Assignment help,Project help, Programming tutors help and suggestion you can send mail at contact@codersarts.com.
Please write your suggestion in comment section below if you find anything incorrect in this blog post.
Comentarios