0

When I open a file, I have to specify the directory that it is in. Is there a way to specify using the current directory instead of writing out the path name? I'm using:

source = os.listdir("../mydirectory")

But the program will only work if it is placed in a directory called "mydirectory". I want the program to work in the directory it is in, no matter what the name is.

def copyfiles(servername):

    source = os.listdir("../mydirectory") # directory where original configs are located
    destination = '//' + servername + r'/c$/remotedir/' # destination server directory
    for files in source:
        if files.endswith("myfile.config"):
            try:
                os.makedirs(destination, exist_ok=True)
                shutil.copy(files,destination)
            except:
Prox
  • 699
  • 5
  • 11
  • 33
  • Possible duplicate of [Find current directory and file's directory](https://stackoverflow.com/questions/5137497/find-current-directory-and-files-directory) – victor Jun 23 '17 at 17:39

3 Answers3

3

this is a pathlib version:

from pathlib import Path
HERE = Path(__file__).parent
source = list((HERE /  "../mydirectory").iterdir())

if you prefer os.path:

import os.path
HERE = os.path.dirname(__file__)
source = os.listdir(os.path.join(HERE, "../mydirectory"))

note: this will often be different from the current working directory

os.getcwd()  #  or '.'

__file__ is the filename of your current python file. HERE is now the path of the directory where your python file lives.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

'.' stands for the current directory.

Błotosmętek
  • 12,717
  • 19
  • 29
  • It's worth mentioning for the sake of completeness that if relative paths _somehow_ don't work, there's always `os.getcwd()`. – cs95 Jun 23 '17 at 17:03
0

try:

os.listdir('./')

or:

os.listdir(os.getcwd())
Dimgold
  • 2,748
  • 5
  • 26
  • 49
  • It's worth noting that if you are using Python 3.x, you can simply use `os.listdir()` without any arguments. Also, the `/` is unnecessary :) – victor Jun 23 '17 at 17:04