python - 如何删除文本文件中的换行符?

标签 python file-io linefeed

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

最佳答案

问题可能不是关于 replacing 或 stripping 额外字符,而是关于当你运行 subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE)。后者实际上返回 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()

我希望这证明是有用的。

关于python - 如何删除文本文件中的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41498175/

相关文章:

python - 在初始化时填充一个 defaultdict

c++ - 使用 CString 在 C++ 中重复一个字符不同次数

asp.net - 扩展 ObjectCache 以创建基于文件的缓存替代方案

java - Java中的回车\换行

python 的生命周期

python - 使用记录器对象而不是使用日志记录有什么好处?

python - 列表列表 : Changing all references with one assignment?

c - 相同的文件,相同的文件大小,但两种不同的内存大小,为什么?

Python winreg - 如何将换行写入 REG_SZ 值

python - 使用 Python 删除 json 文件中的新换行符。