Reputation: 10485
In Python, calling e.g. temp = open(filename,'r').readlines()
results in a list in which each element is a line from the file. However, these strings have a newline character at the end, which I don't want.
How can I get the data without the newlines?
Upvotes: 702
Views: 846489
Reputation: 465
I think the most straightforward solution is calling the splitlines()
function on the file object.
Here's a modification of your code:
temp = open(filename,'r').read().splitlines()
This will return a list of all the lines in the file as a string, with each line breaking at \n
. Essentially, it will eliminate all line breaks.
Reference: https://docs.python.org/3.11/library/stdtypes.html#str.splitlines
Upvotes: 0
Reputation: 2012
To get rid of trailing end-of-line (/n
) characters and of empty list values (''
), try:
f = open(path_sample, "r")
lines = [line.rstrip('\n') for line in f.readlines() if line.strip() != '']
f.close()
Upvotes: 1
Reputation: 11688
If you still want to use readline()
, you can strip the newline as you read each line. It seems both intuitive and seems to fit the python style (at least to me).
file = open("foo", "r")
aLineOfText = file.readLine().strip('\n')
Put this in a loop if you have to read multiple lines. This is a good work-around if the file is too big to be read into memory in one swoop.
Upvotes: 0
Reputation: 408
Use pathlib.Path.read_text(), this opens the file in text mode, reads it and closes the file.
from pathlib import Path
temp = Path(filename).read_text()
Upvotes: 1
Reputation: 4853
My preferred one-liner -- if you don't count from pathlib import Path
:)
lines = Path(filename).read_text().splitlines()
This it auto-closes the file, no need for with open()...
Added in Python 3.5.
https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text
Upvotes: 13
Reputation: 7714
You can read the file as a list easily using a list comprehension
with open("foo.txt", 'r') as f:
lst = [row.rstrip('\n') for row in f]
Upvotes: 2
Reputation: 300
This script here will take lines from file and save every line without newline with ,0 at the end in file2.
file = open("temp.txt", "+r")
file2 = open("res.txt", "+w")
for line in file:
file2.writelines(f"{line.splitlines()[0]},0\n")
file2.close()
if you looked at line, this value is data\n, so we put splitlines()
to make it as an array and [0] to choose the only word data
Upvotes: -2
Reputation: 1769
Reading file one row at the time. Removing unwanted chars from end of the string with str.rstrip(chars)
.
with open(filename, 'r') as fileobj:
for row in fileobj:
print(row.rstrip('\n'))
See also str.strip([chars])
and str.lstrip([chars])
.
Upvotes: 37
Reputation: 101919
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
.
Upvotes: 979
Reputation: 283
I think this is the best option.
temp = [line.strip() for line in file.readlines()]
Upvotes: 25
Reputation: 9
my_file = open("first_file.txt", "r")
for line in my_file.readlines():
if line[-1:] == "\n":
print(line[:-1])
else:
print(line)
my_file.close()
Upvotes: -2
Reputation: 61
Try this:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
Upvotes: 2
Reputation: 319
import csv
with open(filename) as f:
csvreader = csv.reader(f)
for line in csvreader:
print(line[0])
Upvotes: -3