使用 os.system() 调用回显命令选项

echo command option with os.system() call

我是 python 脚本编写的新手,我正在尝试实现 python 等同于 shell cmd echo -e "abc\ncde" >file1

file1 的内容如下所示:

abc cde

我的 python 脚本有:

cmd = "echo -e \"abc\ncde\" >file1" os.system(cmd)

但是,执行此操作时,我的 file1 如下所示:

-e abc cde

'-e` 是 echo 将 \n 识别为换行符的选项,不应写入文件。有解决办法吗?

谢谢!

使用上下文管理器打开文件,然后将数据写入文件。

>>> data = 'abc\ncde'
>>> with open('/tmp/file1.txt','w') as f:
        f.write(data)

$ cat /tmp/file1.txt
abc
cde