How to read a file without newlines?
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
.
Reading a file into variable without newlines
You can do search/replace in bash after reading file content:
options=$(<vm.options)
# replace \n with space
options="${options//$'\n'/ }"
Now examine options
variable:
declare -p options
declare -- options="-Random 1 -Letters2 -Occur 3 -In -Passwords9"
How to read .txt file without .readlines() / replace UTF-8 newline character with \n?
Your file already contains newlines ('\x0a'
is an escape for the exact same character that '\n'
produces). I'm assuming your renderer is sending out HTML though, and HTML doesn't care about newlines in the text (outside of pre
blocks, and other blocks styled similarly).
So either wrap the data in a pre
block, or replace the '\n'
with <br>
tags (which are how HTML says "No, really, I want a line break"), e.g.:
from_text = from_text.replace("\n", "<br>\n")
Leaving in the newlines may be handy to people viewing the source, so I replaced with both the <br>
tag and a newline (Python won't replace in a replacement, so don't worry about infinite replacement just because the newline was part of the replacement).
to read line from file without getting "\n" appended at the end
To remove just the newline at the end:
line = line.rstrip('\n')
The reason readline
keeps the newline character is so you can distinguish between an empty line (has the newline) and the end of the file (empty string).
Related Topics
Python3 Tkinter Set Image Size
How to Count the Number of Files in a Directory Using Python
Get Max Value Comparing Multiple Columns and Return Specific Values
How to Read a Column Without Header from CSV and Save the Output in a Txt File Using Python
How to Convert a Datetime Object to Milliseconds Since Epoch (Unix Time) in Python
Counting the Number of Duplicates in a List
What Is the Most Pythonic Way to Check If Multiple Variables Are Not None
Conditional Row Read of CSV in Pandas
Replacing Values in a Dataframe for Given Indices
Convert String to Python Class Object
How to Test Multiple Variables for Equality Against a Single Value
Suppress Stdout/Stderr Print from Python Functions
No Matching Distribution Found for Tkinter
Import Error: Dll Load Failed in Jupyter Notebook But Working in .Py File
How to Handle Multiple Keys for a Dictionary in Python
Combine Year, Month and Day in Python to Create a Date
Django - How to Retrieve Data in Database in Dropdownlist
What Is the Most Efficient Way to Sum a Dict With Multiple Keys by One Key