Getting Rid of \N When Using .Readlines()

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.

Removing \n from readlines with rstrip( \n )

A tuple doesn't have a method that magically propagates to all string elements.

To do that you have to apply rstrip for all items in a list comprehension to create a list.

j = [x.rstrip("\n") for x in j]

that rebuilds a list with items stripped. Convert to tuple if really needed:

j = tuple(x.rstrip("\n") for x in j)

note that you could avoid this post processing by doing:

readsites = sites.read().splitlines()

instead of sites.readlines() since splitlines splits into lines while removing the termination character if no argument is specified. The only drawback is in the case when the file is huge. In that case, you could encounter a memory issue (memory needed by read + split is doubled). In which case, you could do:

with open("websites.txt",'r') as sites:
readsites = [line.rstrip("\n") for line in sites]

How to readlines without having the \n at the end? (python)

First of all, your code have logical bug.

if savedlines == []:
eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggvalueupgrade = 100
money = eggz * eggvalue

eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

You check wheter savedlines is empty list and set some values accordingly. But, if this is true, following lines will fail with IndexError, since your list is empty. You need to change this to:

if savedlines == []:
eggz = 0
eggvalue = 0.2
chookz = 0
eggzps = 0.0
eggvalueupgrade = 100
money = eggz * eggvalue
else:
eggz = int(savedlines[0])
eggvalue = int(savedlines[1])
chookz = int(savedlines[2])
eggzps = int(savedlines[3])
eggvalueupgrade = int(savedlines[4])
money = int(savedlines[5])

Now, to address the question. After the line:

savedlines = savedfile.readlines()

You should add following line which will strip \n from the end of the lines:

savedlines = [line.rstrip("\n") for line in savedlines]

Remove the newline character in a list read from a file

str.strip() returns a string with leading+trailing whitespace removed, .lstrip and .rstrip for only leading and trailing respectively.

grades.append(lists[i].rstrip('\n').split(','))

cant get rid of trailing \n when reading variable from file in python3 script

You've been going about this the wrong way, that is, converting a list into a string and then trying to manipulate it is overly complicating things. Instead you can remove the trailing new line using rstrip():

>>> s = 'Mr Inbetween\n'
>>> s
'Mr Inbetween\n'
>>> s.rstrip('\n')
'Mr Inbetween'

You can process the lines of a file like this:

os.system(r"grep -R 'title' tmp2 | awk -F '\"' '{print $4}' > guessedtitle ")
with open("./guessedtitle", "r") as myfile2:
for searchterm in myfile2:
searchterm = line.rstrip('\n')
print(searchterm)

This will iterate over all the lines in the file and remove all trailing newline characters before printing the line.

Given that you expect there to be a single line in the file, you can just use use readline() to read the single line. You would still need to remove the trailing new line.

os.system(r"grep -R 'title' tmp2 | awk -F '\"' '{print $4}' > guessedtitle ")
with open("./guessedtitle", "r") as myfile2:
searchterm = myfile2.readline().rstrip('\n')
print(searchterm)

Finally, there are better ways to execute external programs from Python. The subprocess module contains functions to do that.

How to strip newline in string from readline() function?

For anyone needing the answer to this, @rgk has let me know that

answer = lol.readline().strip()

is how to solve my problem :)



Related Topics



Leave a reply



Submit