How can i remove line feed character in text file?

2.6k views Asked by At
import subprocess
cmd = 'tasklist'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
file = open("Process_list.txt", "r+")
for line in proc.stdout:
        file.write(str(line))

file.close()

i just wrote saving process list to text file. But Process_list.txt file has lots of line feed character like \r\n. How can i remove it? i used replace and strip func before

3

There are 3 answers

1
Abdou On BEST ANSWER

The problem may not be so much about replacing or stripping extra characters as it is about what gets returned when you run subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE). The latter actually returns bytes, which may not play so nicely with writing each line to the file. You should be able to convert the bytes to string before writing the lines to the file with the following:

import subprocess
cmd = 'tasklist'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
file = open("Process_list.txt", "r+")
for line in proc.stdout:
        file.write(line.decode('ascii')) # to have each output in one line

file.close()

If you don't want to have each output in one line, then you can strip the newline characters with file.write(line.decode('ascii').strip()).

Moreover, you could have actually used subprocess.getoutput to get an output of string characters and save the outputs to your file:

cmd = 'tasklist'
proc = subprocess.getoutput(cmd)
file.write(proc)
file.close()

I hope this proves useful.

0
elethan On

You will indeed use strip() once again:

In [1]: 'foo\r\n'.strip()
Out[1]: 'foo'

In your case:

file.write(str(line).strip())

You can avoid having to close() your file by using with too:

with open("Process_list.txt", "r+") as file:
    for line in proc.stdout:
        file.write(str(line).strip())

Also, note that str() is only necessary of line is not already a string.

0
Thelmund On

Perhaps you're looking for str.rstrip(). It removes trailing newline and carriage return characters; however, it also removes all trailing whitespace, so be aware of that.