Python - How to read files in multiple ways

February 13, 2021

Read file all in one shot

with open(filepath, 'r') as file:
    data = file.read()

Above code read whole file at once, but if the files have multiple lines, the result string will have new line characters as well.

This code will gets you a single string as whole content

Read file all in one shot and remove newline character

with open(filepath, 'r') as file:
    data = file.read().replace('\n', '')

This code will gets you a single string as whole content

Read all content at once into list of lies

with open('filename') as f:
    lines = f.readlines()

Again, this will give new line characters

Read all content at once into list of files and remove newline character

with open('filename') as f:
    lines = [line.rstrip() for line in f]

Another way to read file at once into list of words and remove newline character

with open(source_file) as f:
    lines = f.read().splitlines()

The best way to open file is with with keyword, as you do not need to close the file explicitly. It will take care of closing the file handle.


Similar Posts

Latest Posts