Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines from file and discard "\n" and "\l" trailing characters

Tags:

python

If I enter the following code:

f = open('/etc/issue', 'r')
out = f.readline()
f.close()
print out

I get:

Ubuntu 14.04.5 LTS \n \l

>>>

if I enter:

out = f.readline().strip()

I get:

Ubuntu 14.04.5 LTS \n \l
>>>

(without new line)

But how do I only get:

Ubuntu 14.04.5 LTS

without "\n \l"?

and what is "\l"?

like image 395
mebus08 Avatar asked Dec 05 '25 06:12

mebus08


2 Answers

\n and \l are not special characters, they are part of the content of the file /etc/issue (see the manpage for issue. They have a special meaning that you can check in the manpage for agetty. \n means "the name of the machine" and \l "the name of the TTY".

If you want to get the release name from the default /etc/issue file in Ubuntu (note that this file may be edited to change the appearance of the login terminal), you can simply do something like:

out = f.readline().split('\\')[0].strip()

A more reliable way of getting the distribution information is using the somewhat obscure lsb_release module (APT package lsb-release):

import lsb_release
release_name = lsb_release.get_distro_information()['DESCRIPTION']
like image 144
jdehesa Avatar answered Dec 08 '25 11:12

jdehesa


There are many ways.

One would be replace them with empty string:

f = open('/etc/issue','r')
out = f.readline()
out = out.replace('\\n', '').replace('\\l', '').strip()
f.close()
print out

Or get rid of the last a few characters:

out = f.readline()[:-6].strip()
like image 45
greedy52 Avatar answered Dec 08 '25 10:12

greedy52



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!