Skip to main content

Python Directory | Python File Handling

 Python Directory and Files Management

If there are a large number of files to handle in your Python program, you can arrange your code within different directories to make things more manageable. 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

We can get the present working directory using the getcwd() method. This method returns the current working directory in the form of a string. We can also use the getcwdb() method to get it as bytes object.
>>> import os

>>> os.getcwd()
'C:\\Program Files\\PyScripter'

>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
The extra backslash implies escape sequence. The print() function will render this properly.
>>> print(os.getcwd())
C:\Program Files\PyScripter

Changing Directory

We can change the current working directory using the chdir() method. The new path that we want to change to must be supplied as a string to this method. We can use both forward slash (/) or the backward slash (\) to separate path elements. It is safer to use escape sequence when using the backward slash.
>>> os.chdir('C:\\Python33')

>>> print(os.getcwd())
C:\Python33

Making a New Directory

We can make a new directory using the mkdir() method. This method takes in the path of the new directory. If the full path is not specified, the new directory is created in the current working directory.
>>> os.mkdir('test')

>>> os.listdir()
['test']



Renaming a Directory or a File

The rename() method can rename a directory or a file. The first argument is the old name and the new name must be supplies as the second argument.
>>> os.listdir()
['test']

>>> os.rename('test','new_one')

>>> os.listdir()
['new_one']

Removing Directory or File

A file can be removed (deleted) using the remove() method. Similarly, the rmdir() method removes an empty directory.
>>> os.listdir()
['new_one', 'old.txt']

>>> os.remove('old.txt')
>>> os.listdir()
['new_one']

>>> os.rmdir('new_one')
>>> os.listdir()
[]



However, note that rmdir() method can only remove empty directories. In order to remove a non-empty directory we can use the rmtree() method inside the shutil module.
>>> os.listdir()
['test']

>>> os.rmdir('test')
Traceback (most recent call last):
...
OSError: [WinError 145] The directory is not empty: 'test'

>>> import shutil

>>> shutil.rmtree('test')
>>> os.listdir()
[]

Ref: Learn python:Python tutorial app

App by Avrram piperidas

Most Popular Course:Data Science of Harvard, MIT, IBM.... 

John Academy: 97% Off on Popular Online Courses



Amazon Best Seller in Baby Products

List Directories and Files

All files and sub directories inside a directory can be known using the listdir() method. This method takes in a path and returns a list of sub directories and files in that path. If no path is specified, it returns from the current working directory.
>>> print(os.getcwd())
C:\Python33

>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']

>>> os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']

Comments

Popular posts from this blog

Python User-Defined Exception | Learn python

  Python Custom Exceptions Python has many built-in exceptions which forces your program to output an error when something in it goes wrong. However, sometimes you may need to create custom exceptions that serves your purpose. In Python, users can define such exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from Exception class. Most of the built-in exceptions are also derived form this class. >>> class CustomError (Exception) : ... pass ... >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError( "An error occurred" ) Traceback (most recent call last): ... __main__.CustomError: An error occurred Here, we have created a user-defined exception called CustomError which is derived from the Exception class. This new exception can be raised, like other exceptions, using the raise statement with an optional error message. When we are develo...

Python Exception Handling | Learn python

  Python Exception Handling - Try, Except and Finally Python has many built-in exceptions which forces your program to output an error when something in it goes wrong. When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash. For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A. If never handled, an error message is spit out and our program come to a sudden, unexpected halt. Catching Exceptions in Python In Python, exceptions can be handled using a try statement. A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. It is up to us, what operations we perform once we have caught the exception. Here is a simple example. # import module sys to get the type of except...

Learn Python basics | Python basics You Should learn before starting python

  Learn Python basics | Python basics You Should learn before starting python  Intro basics First Python Program Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the following prompt − $ python Python 2.4 .3 ( #1, Nov 11 2010, 13:34:43) [GCC 4.1 .2 20080704 (Red Hat 4.1 .2 -48 )] on linux2 Type "help" , "copyright" , "credits" or "license" for more information. >>> Type the following text at the Python prompt and press the Enter: >>> print "Hello, Python!" If you are running new version of Python, then you would need to use print statement with parenthesis as in print ("Hello, Python!");. However in Python version 2.4.3, this produces the following result: Hello, Python! Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finish...