×

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

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Python Tuple Methods

Python Tuple Methods Python has two built-in methods that are used for tuples. The following are the two methods: Method Description count() The tuple.count() method in Python returns the number of times a...

1 minute read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Python email utils

Python is a popular programming language in this growing world. There are many resources to learn python online without spending a single penny. In this article, we will talk about a...

4 minutes read.

What is Collaborative Filtering in ML, Python

Introduction Contents recommendation is a useful tactic for almost any specific technology looking to increase interest, but it frequently calls for a lot of user data and perhaps laborious content tagging...

3 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Check Palindrome in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.