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())
내가
'.strip()'또는'.rstrip()'(예 :'file.write (line.rstrip())')을 원할 수도 있습니다. 'line'은 거의 이미 문자열이므로, 변환은 필요 없습니다. 또한 컨텍스트 관리자를 사용하여 파일을 여는 경우 'with' 키워드를 조사해야합니다. – jedwards
사실'subprocess.Popen (cmd, shell = True, stdout = subprocess.PIPE)'는'bytes'를 반환합니다. 'file.write (str (line))'대신'file.write (line.decode ('ascii'). strip())'를 실행하십시오. – Abdou
'Popen()'은 바이트와 함께 작동하기 때문에 데이터를'encode/decode '해야 할 수도 있습니다. 아니면 바이트 모드'b'로 파일을 열어야합니다. – furas