Jagan
Jagan

Reputation: 37

New line character appended to os.popen().read() command

I am retrieving a file through the below command:

fileName = os.popen('ls -t testfile.txt |head -n1').read()

while printing fileName, I see \n appended.

I know we can remove \n through replace command, but I want to know why this is happening.

Upvotes: 1

Views: 1255

Answers (2)

Shannarra
Shannarra

Reputation: 559

There is a way to do it.

You can pipe the tr command to ls, for example:

ls -A | tr '\n' ' ' | less

Just use the command as:

ls | tr '\n' ' ' | head n-1

So in your Python code you can just

fileName = os.popen("ls -t testfile.txt | tr '\n' ' ' | head n-1").read()[:-1]

This will replace the newline with a space character and then exclude it from the string.

Upvotes: 1

Matteo
Matteo

Reputation: 91

It is the ls command that append a new-line character to the output, you can figure it out opening a terminal and executing the command you want to run by popen

Upvotes: 1

Related Questions