Search code examples
pythonpython-3.xvariablespathrelative-path

Calling for relative paths in Python


I have this below Python script that fetches a file from one location and copies that to another Target location. The below code works just fine if I define the paths with the absolute locations.

I am trying to rather define this using variables, which when done does not execute the script. There is no error that is thrown but the code does not seem to be executed.

Code:

Path_from = r'/Users/user/Desktop/report'
Path_to = r'/Users/user/Desktop/report'

for root, dirs, files in os.walk((os.path.normpath(Path_from)), topdown=False):
        for name in files:
            if name.endswith('{}.txt'.format(date)):
                print
                "Found"
                SourceFolder = os.path.join(root, name)
                shutil.copy2(SourceFolder, Path_to)

I want to change the code from

Path_from = r'/Users/user/Desktop/report'

to

base_path = /Users/user/Desktop/
Path_from = r'base_path/{}'.format(type)

Solution

  • I would recommend you leave all the current working directory concerns to the user - if they want to specify a relative path, they can enter into the directory to which it relates before invoking the python and providing relative paths.

    This is what just about every linux tool and program does - rarely do they take a 'base path', but rather leave the job of providing valid paths relative to the current directory ( or absolute ) to the user.

    If you're dedicated to the idea of taking another parameter as the relative path, it should be pretty straightforward to do. Your example doesn't have valid python syntax, but it's close:

    $ cat t.py
    from os.path import join
    basepath="/tmp"
    pathA = "fileA"
    pathB = "fileB"
    print(join(basepath,pathA))
    print(join(basepath,pathB))
    

    note however that this prevents an absolute path being provided at script execution time.

    You could use a format instead,

    basepath="/tmp"
    pathA = "fileA"
    pathB = "fileB"
    print( "{}/{}".format(basepath, pathA) )
    print( "{}/{}".format(basepath, pathB) )
    

    But then you're assuming that you know how to join paths on the operating system in question, which is why os.path.join exists.