新行字符附加到 os.popen().read() 命令
New line character appended to os.popen().read() command
我正在通过以下命令检索文件:
fileName = os.popen('ls -t testfile.txt |head -n1').read()
在打印 fileName
时,我看到附加了 \n
。
我知道我们可以通过替换命令删除 \n
,但我想知道为什么会这样。
是ls命令在输出后追加一个换行符,你可以打开一个终端并执行你想要的命令运行 来自 popen
是一种方法。
您可以将 tr 命令通过管道传递给 ls,例如:
ls -A | tr '\n' ' ' | less
只需使用如下命令:
ls | tr '\n' ' ' | head n-1
所以在你的Python代码中你可以
fileName = os.popen("ls -t testfile.txt | tr '\n' ' ' | head n-1").read()[:-1]
这会将换行符替换为 space 字符,然后将其从字符串中排除。
我正在通过以下命令检索文件:
fileName = os.popen('ls -t testfile.txt |head -n1').read()
在打印 fileName
时,我看到附加了 \n
。
我知道我们可以通过替换命令删除 \n
,但我想知道为什么会这样。
是ls命令在输出后追加一个换行符,你可以打开一个终端并执行你想要的命令运行 来自 popen
是一种方法。
您可以将 tr 命令通过管道传递给 ls,例如:
ls -A | tr '\n' ' ' | less
只需使用如下命令:
ls | tr '\n' ' ' | head n-1
所以在你的Python代码中你可以
fileName = os.popen("ls -t testfile.txt | tr '\n' ' ' | head n-1").read()[:-1]
这会将换行符替换为 space 字符,然后将其从字符串中排除。