×

Write a String 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 an English-like syntax that is very easy to write and understand, which also reduces the maintenance cost. Python is an interpreted language which means that it uses an interpreter instead of the compiler to run the code.

The interpreted language is processed at the run time thus takes less time to run. Python also has third parties modules and libraries which encourage development and modifying the code.

While working in Python, we need to store data or export some and import some data to the files. The output of a program is not permanent, and it gets destroyed as soon as we close the program, so what if we want to store the output? So, in that case, file handling comes to help us.In this article, we will discusshow to write in text files in Python.

Python provides an in-built function to read and write files, so it is simple to handle files in Python. We can handle two types of files in Python, which are:

  1. Text Files: These are the default text files. In these files, every line of the text is terminated with a special character called End of Line (EOL). It is '\n' by default in normal text files.
  2. Binary Files: These files do not have any End of Line characters, and the data is stored in binary language, which the machine understands.

Writing in Text files.

To write in a text, we use some steps. The steps to writing a string in a file using Python are:

  1. Step 1: The first step is to open the file in WRITE or APPEND mode with the help of the open()  function in Python.
  2. Step 2:The next step is to write in the file using the write() or write lines() functions by passing the string.
  3. Step 3: After everything is done, we can finally close the file using the close() functions.

Now, we will discuss these steps in detail

Opening a File

The syntax for opening the file using the open() function in Python is:

f = open(path_to_file, mode)

Like many functions, the open() function also accepts many arguments, but the mandatory ones are just two, which are:

  1. path_to_file: The path_to_file parameter is used to specify the path of the file on which we want to write the text on.
  2. Mode: The mode parameter is used to assign the permission we want to open the file, e.g., Write, Read, etc.

In this case, we want to write a text file, so the mode we can use are:

  1. w: w mode is used to open the text file with WRITE permissions so that we can write on it. It creates the file if it does not already exist. If we open an existing file, then the data we write gets over-written to it.
  2. The file is created if it does not exist already
  3. . a: a mode is used to open the file with APPEND permission to append the text we want to write. The data we write is appended at the end of the file.

Writing in a File

After opening a file with the open() function, we get a file object returned by the open function. To write the text on the file, we can use the two functions available in this file object which are written () and write lines().

With the write() function, we can write a string to a file, and with the writelines() function, we can write multiple strings by using the list of strings in a file.

We can also pass iterable objects like tuples or a set of strings and not just a list to the writelines() function.

After writing a line in a file, we will need to add a new line character manually.

To add the new line character in a text file we can use the code below:

f.write('\n')

f.writelines('\n')

Writing Text files examples.

Writing using write() function

Below is the example of how we can use the write() function to write a string in a file in Python.

strings = ['Example 1', 'How to write strings in text file in Python']

with open('Example1.txt', 'w') as file:

for line in strings:

file.write(line)

file.write('\n')

Output

After running the above code, a new file called Example1.txt will be created with the following content:

Example1

How to write strings in the text file in Python
Write A String In Python

Note: If the Example1.txt already exists, then this code will overwrite the strings to the original file.

Writing using write lines() function

write lines() function is used to write multiple lines in a text file using Python. Below is the code of using the writelines() function:

strings = ['Example2', 'How to write multiple text lines in file in Python']

with open('readme.txt', 'w') as file:

file.writelines(strings)

Output

The output of the above code will be:

Example2How to write multiple text lines in a file in Python
Write A String In Python

If we want to add every string in the list in a new line, we have to add the new line character in the code manually.

strings = ['Example 3', 'How to write multiple text lines in file in Python']

with open('readme.txt', 'w') as file:

file.writelines('\n'.join(strings))

Output

The output will be a text file with every string in a new line.
Example 3

How to write multiple text lines in a file in Python
Write A String In Python

As you can see, the write mode has overwritten the previous text in the file.

Appending Text File

Let us append some more lines to the file we created in Example 3. To append the strings in a file, we need to open the file with append permission. Let us see the code for appending strings:

multiple_lines = ['', 'Example 4', 'Append new lines' ]

with open('readme.txt', 'a') as file:

file.writelines('\n'.join(multiple_lines))

Output

After running the file, the list multiple_lines will get appended to the file readme.txt

Example 3

How to write multiple text lines in a file in Python

Example 4

Append new lines
Write A String In Python

Related Topics

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Python File Handling

What is the file? The file is a collection of data in a single unit. It is used to store information in the non-volatile memory such as hard-disk. Computer programs generally run on the RAM...

7 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Loan Calculator using PyQt5 in Python

In the following tutorial, we will learn how to build a Loan Calculator application using the PyQt5 library in the Python programming language. So, let's get started. Introduction to the code: The heading...

4 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Managing Multiple Python Versions With pyenv

Introduction If you had ever wished to assist to an application that makes use of several different Python versions but weren't sure whether you would quickly test them all? Do you...

4 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 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 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.

How to uninstall python

To un-install Python, we need to follow different procedures in different operating systems. In this article, we will discuss the un-installation process of Python in Windows, Mac, and Linux operating...

4 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Python exit commands

exit(), quit(), sys.exit(), os._exit() In this tutorial, we will study exit commands used in the Python programming language. Python is undoubtedly the choice of programmer and this is because of the in-built...

3 minutes read.

Python JSON

In this tutorial, we will learn about JSON in the Python programming language. We will focus on its features, Guidelines to be kept in mind while writing its syntax, the...

3 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

Bar Plot in Python

A bar chart or bar graph displays categorical data using rectangular bars with heights or lengths proportionate to the values for the data distributed in the dataset. In a bar...

16 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Python Arithmetic Operators

An arithmetic operator is a mathematical operator that is used to operate on two operands. Based on the operator used, action is performed on the operands, and output is delivered. Following...

3 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute read.