如何删除文本文件中的换行符?
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()
我刚刚将保存进程列表写入文本文件。但是 Process_list.txt 文件有很多像 \r\n 这样的换行符。我怎样才能删除它?我之前用过 replace 和 strip func
你确实会再次使用strip()
:
In [1]: 'foo\r\n'.strip()
Out[1]: 'foo'
你的情况:
file.write(str(line).strip())
您也可以使用 with
来避免 close()
您的文件:
with open("Process_list.txt", "r+") as file:
for line in proc.stdout:
file.write(str(line).strip())
此外,请注意 str()
仅当 line
还不是字符串时才需要。
也许您正在寻找 str.rstrip()。它删除尾随的换行符和回车符 return 字符;但是,它还会删除所有尾随空格,因此请注意这一点。
问题可能不在于 replac
ing 或 strip
ping 额外字符,而在于当您 运行 subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
时返回的内容。后者实际上是 returns bytes
,在将每一行写入文件时可能效果不佳。在将行写入文件之前,您应该能够将 bytes
转换为 string
:
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())
.
去掉换行符
此外,您实际上可以使用 subprocess.getoutput
来获取字符串字符的输出并将输出保存到您的文件中:
cmd = 'tasklist'
proc = subprocess.getoutput(cmd)
file.write(proc)
file.close()
希望这有用。
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 这样的换行符。我怎样才能删除它?我之前用过 replace 和 strip func
你确实会再次使用strip()
:
In [1]: 'foo\r\n'.strip()
Out[1]: 'foo'
你的情况:
file.write(str(line).strip())
您也可以使用 with
来避免 close()
您的文件:
with open("Process_list.txt", "r+") as file:
for line in proc.stdout:
file.write(str(line).strip())
此外,请注意 str()
仅当 line
还不是字符串时才需要。
也许您正在寻找 str.rstrip()。它删除尾随的换行符和回车符 return 字符;但是,它还会删除所有尾随空格,因此请注意这一点。
问题可能不在于 replac
ing 或 strip
ping 额外字符,而在于当您 运行 subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
时返回的内容。后者实际上是 returns bytes
,在将每一行写入文件时可能效果不佳。在将行写入文件之前,您应该能够将 bytes
转换为 string
:
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())
.
此外,您实际上可以使用 subprocess.getoutput
来获取字符串字符的输出并将输出保存到您的文件中:
cmd = 'tasklist'
proc = subprocess.getoutput(cmd)
file.write(proc)
file.close()
希望这有用。