当前位置: 代码迷 >> python >> 平台无关的文件写入方式
  详细解决方案

平台无关的文件写入方式

热度:107   发布时间:2023-07-16 09:37:55.0
def writeFile(filename):
    prose = r"<?xml version='1.0' encoding='UTF-8'?>"
    startTag = r'<Books>'
    endTag = r'</Books>'
    with open(filename, "+a" ) as f:
        f.write(prose)
        f.write('\n')
        f.write(startTag)
        f.write('\n')
        f.write(endTag)

我如何使该功能平台独立,因此它也可以在Windows和Linux / Unix上运行,因为/ n是Windows上的换行符。

我在Python 3.3上

您需要查看模块。 特别是检查os.linesepos.sep

os.linesep将为您提供正确的新行分隔符,您无需检查platorm / os版本

os.sep将为您提供路径名组件的分隔符,并且您无需再次检查平台/操作系统版本

  相关解决方案