How to remove n from string in python when reading file

Here are various optimisations and applications of proper Python style to make your code a lot neater. I've put in some optional code using the csv module, which is more desirable than parsing it manually. I've also put in a bit of namedtuple goodness, but I don't use the attributes that then provides. Names of the parts of the namedtuple are inaccurate, you'll need to correct them.

import csv
from collections import namedtuple
from time import localtime, strftime

# Method one, reading the file into lists manually (less desirable)
with open('grades.dat') as files:
    grades = [[e.strip() for e in s.split(',')] for s in files]

# Method two, using csv and namedtuple
StudentRecord = namedtuple('StudentRecord', 'id, lastname, firstname, something, homework1, homework2, homework3, homework4, homework5, homework6, homework7, exam1, exam2, exam3')
grades = map(StudentRecord._make, csv.reader(open('grades.dat')))
# Now you could have student.id, student.lastname, etc.
# Skipping the namedtuple, you could do grades = map(tuple, csv.reader(open('grades.dat')))

request = open('requests.dat', 'w')
cont = 'y'

while cont.lower() == 'y':
    answer = raw_input('Please enter the Student I.D. of whom you are looking: ')
    for student in grades:
        if answer == student[0]:
            print '%s, %s      %s      %s' % (student[1], student[2], student[0], student[3])
            time = strftime('%a, %b %d %Y %H:%M:%S', localtime())
            print time
            print 'Exams - %s, %s, %s' % student[11:14]
            print 'Homework - %s, %s, %s, %s, %s, %s, %s' % student[4:11]
            total = sum(int(x) for x in student[4:14])
            print 'Total points earned - %d' % total
            grade = total / 5.5
            if grade >= 90:
                letter = 'an A'
            elif grade >= 80:
                letter = 'a B'
            elif grade >= 70:
                letter = 'a C'
            elif grade >= 60:
                letter = 'a D'
            else:
                letter = 'an F'

            if letter = 'an A':
                print 'Grade: %s, that is equal to %s.' % (grade, letter)
            else:
                print 'Grade: %.2f, that is equal to %s.' % (grade, letter)

            request.write('%s %s, %s %s\n' % (student[0], student[1], student[2], time))


    print
    cont = raw_input('Would you like to search again? ')

print 'Goodbye.'

In this article, we will learn to read a text file into a string variable and strip newlines.

Table Of Contents

  • Read a text file into a string and strip newlines using file.read() and replace()
  • Read a text file into a string and strip newlines using rstrip()
  • Read a text file into a string and strip newlines using List Comprehension

Strip newlines means removing the \n from last of the string. To open a file in python , we use open() method.It returns a file object.

SYNTAX of open():

open(file, mode)

It recieves only two parameters :
– Path or name of the file you want to open.
– The mode in which you want to open that particular file.

Advertisements

See this code below :

CODE :

with open('example.txt','r') as file:
    text = file.readlines()
    print(type(text))
    print(text)

OUTPUT :

<class 'list'>
['This is the first line.\n', 'This is the second line.\n', 'This is the third line\n', 'This is the fouth line.\n', 'This is the fifth line.\n']

As you can see in output, Text in file example.txt gets printed in a list and after every line there is \n which is called newline. Data type of variable text is also a list type.

The contents of our example.txt is,

This is the first line.
This is the second line.
This is the third line
This is the fouth line.
This is the fifth line.

Create a example.txt file and save at same location where your code file is. Now we will read about different methods. Read and try this code on your machine. I have used Python version Python 3.10.1.

In the problem above, you can see readlines() method has been used to read the data. But now we will use read() method. The read() method iterates over every single character, that means read() method reads character wise. Then using the replace() function, we can replace all occurrences of ‘\n’ with an empty string.

EXAMPLE :*

with open('example.txt','r') as file:
    text = file.read().replace('\n', ' ')
    print(type(text))
    print(text)

OUTPUT :

<class 'str'>
This is the first line. This is the second line. This is the third line This is the fouth line. This is the fifth line.

Now you can see, by using read() and replace(), we have sucessfully removed the \n and saved all the data from a text file to a single string object.

Read a text file into a string and strip newlines using rstrip()

The rstrip() method is another method through which we can strip newlines in python string.

What is rstrip() method ?

The rstrip() method removes any whitespace or new line characters which from the end of a line. It recieves only one optional parameter, which is the specific character that you want to remove from the end of the line.

EXAMPLE :

with open('example.txt','r') as file:
    text = file.read().rstrip()
    print(type(text))
    print(text)

OUTPUT :

<class 'str'>
This is the first line.
This is the second line.
This is the third line
This is the fouth line.
This is the fifth line.

In output above you can see data type is of type str and there is no any \n. Unlike repalce() method all the names are also in different lines.
There is also a similar to rstrip() method which is strip(). The strip() method removes characters from both sides (starting and beginning of a line).

Read a text file into a string and strip newlines using List Comprehension

Iterate over each line of file and strip the newline characters from the end of each line. Then join all these lines back to a single string.

Example:

with open('example.txt','r') as file:
    text = " ".join(line.rstrip() for line in file)
    print(text)

Output:

This is the first line. This is the second line. This is the third line This is the fouth line. This is the fifth line.

Summary

So we read about three different methods, to read a text file into a string variable and strip newlines in python. You can use all three different methods from above depending upon your use but the easiest and most commonly used is read() method. Because it reads characterwise and removes the newlines from the given string file. rstrip() and strip() methods are also used when you have any specific characters you want to remove.

How do you remove N from a file in Python?

Python File I/O: Remove newline characters from a file.
Sample Solution:.
Python Code: def remove_newlines(fname): flist = open(fname).readlines() return [s.rstrip('\n') for s in flist] print(remove_newlines("test.txt")) ... .
Flowchart:.
Python Code Editor: ... .
Have another way to solve this solution?.

How do I read a text file without an N in Python?

Read a File Without Newlines in Python.
Use the strip() and the rstrip() Methods to Read a Line Without a Newline in Python..
Use the splitlines and the split() Methods to Read a Line Without a Newline in Python..
Use slicing or the [] Operator to Read a Line Without a Newline in Python..

How do you ignore N in Python?

Remove \n From String Using regex Method in Python To remove \n from the string, we can use the re. sub() method.

Does readline () take in the \n at the end of line?

Properties of Python file readline() method The readline() method only reads one complete line at a time. It adds a newline ( "\n" ) at the end of every line. It returns a string value if the file is opened in normal read “r” mode. This method returns the binary object if the file is opened in the binary mode “b”.