w3resource logo


Python Exercises

Python File I/O: Remove newline characters from a file

Python File I/O: Exercise-17 with Solution

Write a Python program to 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"))

Output :

['lasith madushanka']

Python Code Editor:

def remove_newlines(fname):
    flist = open(fname).readlines()
    return [s.rstrip('\n') for s in flist]

print(remove_newlines("test.txt"))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program