2017-01-06 6 views
2
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() 

방금 ​​프로세스 목록을 텍스트 파일에 저장했습니다. 하지만 Process_list.txt 파일에는 \ r \ n과 같은 줄 바꿈 문자가 많이 있습니다. 어떻게 제거 할 수 있습니까?텍스트 파일에서 줄 바꿈 문자를 제거하려면 어떻게해야합니까?

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

를 귀하의 경우 : 당신은 너무 with를 사용하여 close()에 파일을 것을 방지 할 수

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

내가

+0

'.strip()'또는'.rstrip()'(예 :'file.write (line.rstrip())')을 원할 수도 있습니다. 'line'은 거의 이미 문자열이므로, 변환은 필요 없습니다. 또한 컨텍스트 관리자를 사용하여 파일을 여는 경우 'with' 키워드를 조사해야합니다. – jedwards

+1

사실'subprocess.Popen (cmd, shell = True, stdout = subprocess.PIPE)'는'bytes'를 반환합니다. 'file.write (str (line))'대신'file.write (line.decode ('ascii'). strip())'를 실행하십시오. – Abdou

+0

'Popen()'은 바이트와 함께 작동하기 때문에 데이터를'encode/decode '해야 할 수도 있습니다. 아니면 바이트 모드'b'로 파일을 열어야합니다. – furas

답변

3

ing 또는 strip에 대해 여분의 문자를 ping하는 것이일 때 반환되는 것과 관련하여 문제가되지 않을 수 있습니다. 후자는 실제로 bytes을 반환하는데, 이는 각 행을 파일에 기록 할 때 좋게 재생되지 않을 수 있습니다. 당신은 함께 파일에 줄을 쓰기 전에 stringbytes을 변환 할 수 있어야 다음 한 줄에 각 출력을하지 않으려면

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() 

은 다음과 개행 문자를 제거 할 수 있습니다 file.write(line.decode('ascii').strip()). 나는이 유용 증명 희망

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

을 :

또한, 당신은 실제로 문자열 문자의 출력을 얻을 파일에 출력을 저장 subprocess.getoutput을 사용했을 수 있습니다.

+0

정말 고맙습니다. – Gripex

1

당신은 참으로 다시 한 번 strip()를 사용하기 전에 교체 스트립 FUNC 사용 :

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

또한, str()line이 (가) 아직 필요하지 않습니다.

1

아마 당신은 str.rstrip()을 찾고 있습니다. 그것은 후행 개행 문자와 캐리지 리턴 문자를 제거합니다. 그러나 후행 공백도 모두 제거되므로주의해야합니다.