Print a new line in text File in Python

Hello friends, today we will learn about how you can manipulate text file data in Python. In this tutorial, we will be focusing on how to print a new line while reading a text file and write data on it in Python. When the file pointer (a cursor that determines the location from where read, write, or append operations should from) encounters a new line character in the text file it should print a new line. It should ignore the extra newlines and whitespaces which aren’t followed by an alphabet or a number.

Table of Contents :

  • Read a text file.
  • Print a new line in the text file in Python.
  • Write on a text file.

To perform the above activity on a text file, the first step is to open the text file from where you want the data.

Sample Code :

f = open("sample.txt", "r")

Contents of sample.txt :

This is CodeSpeedy. 
We provide digital and tech solutions for businesses. 
Our team is always committed to fulfilling your requirements.

Read a Text File :

Python provides us with three functions to read the data:read(), readline(), and readlines(). The read() function reads the entire file from beginning to end and returns a string. The readline() function reads a single line and returns a string. The readlines() function returns a list of all the sentences present in the text file.

Sample Code :

s = f.read()
s1 = f.readline()
s2 = f.readlines()

print(s)
print(s1)
print(s2)

Output :

This is CodeSpeedy. 
We provide digital and tech solutions for businesses. 
Our team is always committed to fulfilling your requirements.

This is CodeSpeedy. 

['This is CodeSpeedy. \n', 'We provide digital and tech solutions for businesses. \n', 'Our team is always committed to fulfilling your requirements.']

Print a new line in text file in Python :

Let’s focus on manipulating the text file data. I want to print a newline every time the file pointer encounters a newline character. However, no new line should be printed after the last line. It should also ensure to ignore unnecessary newline characters and whitespace which aren’t followed by an alphabet or a number.

Code :

f = open("sample.txt", "r")
s = f.read()

for i in range(0, len(s)):
    if s[i] == '\n' and i != len(s)-1:
        if s[i+1] == '\n':
            continue
        if s[i+1].isspace() and not s[i+2].isalnum():
            continue
        else:
            print('\n')
    else:
        print(s[i], end = "")

In this example, I’ve opened the sample.txt file in read mode and used the read() function to retrieve the text file data and stored it in a temporary variable, s. I’ve used a for loop from 0 to the length of the string, s to iterate over the retrieved data. Now check whether the character at the ith index is a newline character or not and if the value of i is not equal to one less than the length of the string, s. If this condition is false, print the character. If the latter is true, check whether the next character in s is a newline character or whitespace not followed by an alphabet or number, then ignore the sentence. However, if the latter is false print a newline.

Input :

This is CodeSpeedy.


We provide digital and tech solutions for businesses. 

 Our team is always committed to fulfilling your requirements.
   

Output :

This is CodeSpeedy.

We provide digital and tech solutions for businesses. 

 Our team is always committed to fulfilling your requirements.

Write on text file :

Let’s focus on writing data on text files. As seen earlier, I manipulated the text file data. Now I wish to store that manipulated data in a new text file. You can check out the tutorial on how to create a text file in Python.

Code :

f = open("sample.txt", "r")
s = f.read()
f.close()

s1 = ""

for i in range(0, len(s)):
    if s[i] == '\n' and i != len(s)-1:
        if s[i+1] == '\n':
            continue
        if s[i+1].isspace() and not s[i+2].isalnum():
            continue
        else:
            s1 += '\n\n'
    else:
        if i == len(s)-1:
            break
        s1 += s[i]


f1 = open("output.txt", "w")
f1.write(s1)

f1.close()

I’ve retrieved the data from the sample.txt as shown in the former example. I’ve added a for loop here as well to iterate over the retrieved data. However this time instead of printing the data on the console I have added the specific character to an empty string s1. After the loop has terminated, I opened a new text file under the name output.txt in write mode. Using the write() function I’ve written the string s1 in the new text file and closed the file after the operation.

Output text file :

This is CodeSpeedy.

We provide digital and tech solutions for businesses. 

 Our team is always committed to fulfilling your requirements.

Thus we’ve successfully learned how to open, read and manipulate text files and their data.

Leave a Reply

Your email address will not be published. Required fields are marked *