简体   繁体   中英

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

The problem may not be so much about replac ing or strip ping 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM