Hướng dẫn python readlines without n

You can read the whole file and split lines using str.splitlines:

temp = file.read().splitlines()

Or you can strip the newline by hand:

temp = [line[:-1] for line in file]

Note: this last solution only works if the file ends with a newline, otherwise the last line will lose a character.

This assumption is true in most cases (especially for files created by text editors, which often do add an ending newline anyway).

If you want to avoid this you can add a newline at the end of file:

with open(the_file, 'r+') as f:
    f.seek(-1, 2)  # go at the end of the file
    if f.read(1) != '\n':
        # add missing newline if not already present
        f.write('\n')
        f.flush()
        f.seek(0)
    lines = [line[:-1] for line in f]

Or a simpler alternative is to strip the newline instead:

[line.rstrip('\n') for line in file]

Or even, although pretty unreadable:

[line[:-(line[-1] == '\n') or len(line)+1] for line in file]

Which exploits the fact that the return value of or isn't a boolean, but the object that was evaluated true or false.


The readlines method is actually equivalent to:

def readlines(self):
    lines = []
    for line in iter(self.readline, ''):
        lines.append(line)
    return lines

# or equivalently

def readlines(self):
    lines = []
    while True:
        line = self.readline()
        if not line:
            break
        lines.append(line)
    return lines

Since readline() keeps the newline also readlines() keeps it.

Note: for symmetry to readlines() the writelines() method does not add ending newlines, so f2.writelines(f.readlines()) produces an exact copy of f in f2.

  1. HowTo
  2. Python How-To's
  3. Read a File Without Newlines in Python

Created: July-01, 2021 | Updated: August-10, 2021

  1. Use the strip() and the rstrip() Methods to Read a Line Without a Newline in Python
  2. Use the splitlines and the split() Methods to Read a Line Without a Newline in Python
  3. Use slicing or the [] Operator to Read a Line Without a Newline in Python
  4. Use the replace() Method to Read a Line Without a Newline in Python

File handling such as editing a file, opening a file, and reading a file can easily be carried out in Python. Reading a file in Python is a very common task that any user performs before making any changes to the file.

While reading the file, the new line character \n is used to denote the end of a file and the beginning of the next line. This tutorial will demonstrate how to readline without a newline in Python.

Use the strip() and the rstrip() Methods to Read a Line Without a Newline in Python

The strip() method in Python helps in omitting the spaces that are present at the beginning (leading) and at the end (trailing). Besides white spaces, the strip() method also includes the newline characters.

Here’s an example you can follow.

with open("randomfile.txt", "r") as file:
    newline_break = ""
    for readline in file: 
        line_strip = readline.strip()
        newline_break += line_strip
    print(newline_break)

The open() is used to open the file. Note that the strip() method will get rid of the newline and the whitespaces at the beginning and the end in the example above. To keep the whitespaces and just omit the newline, the \n command is passed as an argument or a parameter to the strip() method.

We can also use the rstrip() method because the strip() method omits both the leading and the trailing spaces. On the other hand, the rstrip() method just removes the trailing spaces or characters. This method is useful because the newline is present at the end of every string. We can also mention the newline character by \n.

Follow this example below.

with open("randomfile.txt", "r") as file:
    newline_break = ""
    for readline in file:
        line_strip = line.rstrip('\n')
        newline_break += line_strip
    print(newline_break)

Use the splitlines and the split() Methods to Read a Line Without a Newline in Python

The splitlines() method in Python helps split a set of strings into a list. Each string in the set of the string is an element of the list. Thus, the splitlines() method splits the string wherever the newline is present.

with open("randomfile.txt", "r") as file:
    readline=file.read().splitlines()
    print(readline)

Here, note that the point where the split takes place is not mentioned. So, to mention the point where the split should take place manually, the split() method is used. This method performs the same task as the splitlines() method, but it is a little more precise.

with open("randomfile.txt", "r") as file:
    readline=file.read().split("\n")
    print(readline)

Use slicing or the [] Operator to Read a Line Without a Newline in Python

The slicing operator in Python helps in accessing different parts of a sequence or string separately. The slicing operator is defined as: string[starting index : ending index : step value].

Here’s an example you can follow.

with open("randomfile.txt", "r") as file:
    newline_break = ""
    for readline in file: 
        line_strip = line[:-1]
        newline_break += line_strip
    print(newline_break)

Note that in the example above, we removed the last character of every string with the help of negative slicing, for example, [:-1].

Use the replace() Method to Read a Line Without a Newline in Python

As the name suggests, the replace() is a built-in Python function used to return a string in which a substring with all its occurrences is replaced by another substring.

Follow this example below.

with open("randomfile.txt", "r") as file:
    newline_break = ""
    for readline in file:
        line_strip = line.replace('\n', " ")
        newline_break += line_strip
    print(newline_break)

Related Article - Python File

  • Get All the Files of a Directory
  • Delete a File and Directory in Python
  • Append Text to a File in Python
  • Check if a File Exists in Python