Reading a file without newlines using read() and str.rstrip()
In this approach we iterate through each line of the file and use the str.rstrip() method to remove the trailing newline character (‘\n’) from each line. This method strips the newline character from the right end of the string.
Syntax: str.rstrip('\n')
Example: This example uses str.rstrip() method to read a file without newlines in Python.
content = ''
with open('file.txt', 'r') as file:
for line in file:
content += line.rstrip('\n')
print(content)
Output:
Hello Userwelcome tow3wiki
Read a file without newlines in Python
When working with files in Python, it’s common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we’ll explore different approaches to reading a file without newlines in Python.
Read a file without newlines in Python
Below are the possible approaches to read a file without newlines in Python:
- Using read() and str.replace()
- Using read() and str.rstrip()
Text file:
Hello User
welcome to
Geeks
For
Geeks