Python Files

File Handling is an important aspect of the Python Programming language as it is used in web applications. We can create files, read files, write in files, can update files, and can also delete files.

A file can be handled in two ways i.e. Binary(b) and Text(t). A file in Python is also saved with the extension of .txt.

Open() Function

So the first function of file handling is open() and this function will return a file object. There is one important point that you also have to close a file once opened. A file is opened using and closed using f.close() . This open() function takes two parameters:-

  1. filename
  2. mode

There are a total of 4 members to open a file in python:-

  1. "r" = Read - Opens a file for reading.
  2. "w" = Write - Opens a file for Writing.
  3. "a" = Append - Opens a file for Appending.
  4. "r+" = Read and Write - Opens a file for Reading and Writing.

The syntax for opening a file:-

Opening a file in reading mode:-

The above-given syntax is for opening files in reading mode and also the file will be opened in text mode as a file is opened by default in the same mode.

Reading a file on a server

Let's consider a file named file1.txt saved in the same folder as python

To read the above file we will use open() to open the file and read() to read the file.

To read lines in python files we use a function known as readlines() but it will read only a single line.

If you want to read more lines then you have to add more readline() functions. For eg- if you want to read 3 lines then you have to use the readline() function thrice.

Writing in a File

"a" = will append at the end of the line

"w" = will overwrite the content

Append the content

Now we will take an example where we will append the file:-

As you can see that the data has been added at the end of file1.

Now the data from file1 has been removed and the date of file1 has been updated.

Delete a File

In python, you can delete a file using the remove command. Now we will remove the file named file1.txt every python file is removed using import of os module.

Python Directories

Each file in python contains a directory. The os module in python helps in creating, removing, and changing directories.

Syntax of Python Directories:-

Now we will create a test directory in a current directory:-

chdir() method

To change a current directory we use chdir() method. Generally, it takes an argument, which is the name of the directory which we want as our current directory.

rmdir() method

To delete a directory we use the rmdir() method which is passed as an argument in the method.

Exception in Python

In the Python programming language, when a script encounters a situation which it cannot cope up with, then it raises an exception. An exception is a Python object which represents an error in the program. There are several exception methods in python:-

  1. Exception - Used for all exceptions
  2. StopIteration - Occurs when the next() method does not point to any object
  3. StandardError - Base class for all built-in exceptions
  4. ZeroDivisionError - Raised when division or modulo by zero takes place for all numeric types.
  5. FloatingPointError - Raised when any floating-point calculation fails
  6. KeyError - Raised when a specific key is not found in the directory
  7. SyntaxError - Raised when there is an error in syntax
  8. IndentationError - Raised when indentation is not done properly
  9. ValueError - Raised when arguments contain invalid values
  10. RuntimeError - Raised when a generated error does not fall into any category.

There are several more errors in Python.

Exception Handling

To handle exceptions in python we use try: except. If you found something suspicious in your code which may raise an exception then you can defend your program by placing the suspicious code in a try: block. After that add an except statement, followed by a block of code that will handle the problem easily.

The syntax for Try Except:-

User-Defined Exception

Python is a language that allows you to create your exceptions by deriving some classes from the built-in exceptions. Now we will create an exception using Runtime Error. This is very useful when we need to display more accurate information when an exception is caught.

In the try block, the user-defined exception is raised and after that, it is caught in the except block. The variable e is used to create an instance of the class Network error.

I hope that you had easily understood the concept of files in python. You can visit my youtube channel for more help regarding this topic.

Thanks for reading. Hope you liked it. Many more to come in the future.

Note:- The amazing article used in this post is designed by Victor Korchuk

Get the latest episodes directly in your inbox