×

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

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Python Call Function

In this article, you will learn about calling a function in Python. But before learning this, we should know about functions in Python.So, let’s get some overview of functions in...

6 minutes read.

Run exec python from PHP

PHP (which is a recursive abbreviation for PHP Hypertext Preprocessor) is one of the most broadly involved web improvement innovations on the planet. PHP code utilized for creating sites and...

4 minutes read.

Working with files 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...

5 minutes read.

Python Dictionary get() method

Python Dictionary get() method The dictionary.get() method returns the value of the item with the specified key. Syntax dictionary.get(keyname, value) Parameter keyname- This parameter represents the key to be searched in the dictionary. value- The parameter...

1 minute read.

Python Function

Python Function A Python function is a reusable, organized block of code that is used to perform the specific task. The functions are the appropriate way to divide an extensive program into a...

7 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python List append() Method

Python List append() Method The list.append() method in Python adds or appends an item to the end of the list. Syntax list.append(x) Parameter x: It is a required parameter that represents an element of any type (string, number,...

1 minute read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.

Python Read CSV file

The CSV stands for “comma-separated value,” which is defined as a simple file format that is used to store data into a tabular form such as a database or spreadsheet. It is...

7 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

CatPlot in Python

Python Seaborn Library Seaborn is a superb Python tool for displaying graphical statistics graphing. Seaborn provides different color schemes and attractive default styles to facilitate the creation of various statistics charts...

8 minutes read.