Search code examples
pythonfile-iolinefeed

How can i remove line feed character in text file?


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


Solution

  • 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.