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

前端 未结 9 1658
日久生厌
日久生厌 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条回答
  • 2020-11-28 19:55

    Use:

    import os
    print os.sep
    

    to see how separator looks on a current OS.
    In your code you can use:

    import os
    path = os.path.join('folder_name', 'file_name')
    
    0 讨论(0)
  • 2020-11-28 20:04

    You can use "os.sep "

     import os
     pathfile=os.path.dirname(templateFile)
     directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
     rootTree.write(directory)
    
    0 讨论(0)
  • 2020-11-28 20:05

    Do a import os and then use os.sep

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 20:07

    If you are fortunate enough to be running Python 3.4+, you can use pathlib:

    from pathlib import Path
    
    path = Path(dir, subdir, filename)  # returns a path of the system's path flavour
    

    or, equivalently,

    path = Path(dir) / subdir / filename
    
    0 讨论(0)
  • 2020-11-28 20:09

    Use os.path.join(). Example: os.path.join(pathfile,"output","log.txt").

    In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))

    0 讨论(0)
提交回复
热议问题