独立于平台的文件写入方式

2024-09-26 22:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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上的新行字符。在

我使用的是python3.3


Tags: versiondefaswithxmlopenfilenamebooks
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:05

您需要查找os模块。特别是检查os.linesep和{}。在

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

在九月将为路径名组件提供分隔符,而且您不需要检查平台/操作系统版本

相关问题 更多 >

    热门问题