How to use “/” (directory separator) in both Linux and Windows in Python?

前端 未结 9 1661
日久生厌
日久生厌 2020-11-28 19:43

I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use

9条回答
  •  -上瘾入骨i
    2020-11-28 20:05

    Don't build directory and file names your self, use python's included libraries.

    In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.

    Your example would be

    pathfile=os.path.dirname(templateFile)
    p = os.path.join(pathfile, 'output')
    p = os.path.join( p, 'log.txt')
    rootTree.write(p)
    

提交回复
热议问题