×

How to create a file in Python?

How to create a file in python?

Files provide us a convenient way of storing our information. Once we have our data, the next task is to store it so that it can be accessed in the future for various purposes. And here comes ‘files’ to rescue us from the incessant worry of unorganized work.

In python, we can read them, write them and append them as we do normally with our files.

Here we will discuss how we can-

  1. Create a file in Python
  2. Open a file in Python
  3. Append a file in Python
  4. Read a file line by line
  5. File modes present in Python

Before this let us understand some basic terminologies which act as a prerequisite to grasp the concept of File Handling in Python.

Absolute and Relative Path

An absolute path is the one that tells us about the exact location of our file with the help of a complete directory list whereas when we talk about a relative path we have to merge it with another path for accessing our file.

Example-

C:\Subjects\Tutorial&Examples\CS.

The above-given path is the absolute path.

Subjects\Tutorial&Examples is the example of the relative path as it gives us the complete information when it merges with other details of the path.

Types of Files

There are two types of files-

  1. Text Files
  2. Text files are a collection of characters that are processed sequentially.
  3. Reading, writing, and appending are the operations that can be performed on such files.
  1. Binary Files
  2. Binary files are those files that contain all types of data in the binary format for further processing.
  3. Examples of binary files are images, spreadsheets, videos, etc.
  4. They are a collection of bytes.

Creating a File in Python

A file can be created in Python using the append mode. If we open a file and specify the access mode as ‘a’ then it would create a file if it doesn’t exist.

Syntax

fobj = open(“Mydoc.txt”,”a”)

Now, let us see how we can open a file in Python-

Files can be opened in Python using the open() function. This function creates an object which is used to call methods.

The syntax of open() function is-

fobj=open(“filename”, “access mode”)

Here,

The filename is the name of the file which we want to access.

Access mode refers to the mode in which we would like to open it.

We will discuss various access modes in the later section of this article.

Next is to see how we can close a file in Python-

The syntax for closing a file is-

Fobj.close()

Features of close() method-

  1. It closes the file object.
  2. Once we use this, we can't perform a read or write operation on our file.
  3. It frees up the allocated resources of the system.

Appending a file in Python

Appending means adding more content to a file that is made already. We can use the access modes 'a' or 'ab' to append a file depending upon its type (text or binary).

The syntax for the same is-

fobj = open(“fp.txt”,”a”)

If we specify the access mode as “w” or “wb” then it will overwrite the contents of our existing file.

Let us see how we can read a file in Python

The files in Python can be read using two methods-

  1. read() – It is used to read a string in an opened file.
  2. readline() – It is used to read a single line from the file.

Implementation of read() method

 fobj = open(“fp.txt”, “r”)
 print(fobj.read(9))
 fobj.close()
 Implementation of readline() method
 fobj = open(“fp.txt” , “r”)
 print(“Line 1: “,fobj.readline())
 fobj.close() 

Types of File Mode present in Python:

  1. r – this opens the file to read only and it is the default mode.
  2. rb – this opens a file to read in binary format.
  3. r+ - this opens the file for reading & writing.
  4. rb+ - this opens the file for reading & writing in binary format.
  5. w – it opens the file to write only. If the file doesn't exist it is created using this or if it exists the contents are overwritten.
  6. w+ - it opens the file for reading and writing. If the file doesn't exist it is created using this or if it exists the contents are overwritten.
  7. wb - this opens the file for reading & writing in binary format.
  8. a – it opens a file to append.
  9. ab – the file is opened in binary format for appending.

Related Topics

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Allocate a minimum number of pages in python

You have given a sorted array of size n which represents the number of pages in n different books and an integer value which denotes the number of students. We...

4 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

Python Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Insertion Sort using Python

Insertion sort is a type of sorting technique that is used for sorting an array with random elements. Using sorting methods, any unsorted array can be sorted into ascending or...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

How to Compare two Lists in Python?

How to Compare two Lists in Python The list is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets [...

4 minutes read.

Python Tkinter Tutorial

What is Tkinter? Tkinter is GUI library of Python. When we integrated Tinkter with Python, it provides an easy and quick way to develop GUI applications. It provides the Tk GUI...

14 minutes read.