1

I have two file in directory abc

test.py
hello.txt

File test.py:

import os.path

if os.path.exists('hello.txt'):
  print('yes')
else:
  print('no')

when execute test.py in same directory, the output is, as I'd expect, 'yes'

abc > python test.py

output: yes

but when try to execute form other directory

~ > python ~/Desktop/abc/test.py

output: no

how to correct this

# the real case
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)

it works when executing within directory abc but fails form outside.

danicotra
  • 1,333
  • 2
  • 15
  • 34
zen29d
  • 61
  • 7
  • 1
    Give a complete path like `D:/harsha/inputs/abc.txt` This will execute correctly in both ways. – Harsha Biyani Dec 04 '19 at 18:23
  • 2
    Perhaps you need to give the absolute path in stead of the relative path. – Arkistarvh Kltzuonstev Dec 04 '19 at 18:23
  • Do you want to look for the pickle file _in a fixed location_, or do you want to look for it _in the same directory as the python script_? – John Gordon Dec 04 '19 at 18:26
  • @JohnGordon , I don't want lock the file location, its moves around quite – zen29d Dec 04 '19 at 18:33
  • Okay, so how is the program supposed to know where to look for it? – John Gordon Dec 04 '19 at 18:34
  • os.path.exists is not relative... I don’t know what to replace it with.. when run python module its works but when trying to execute from shell its fails, is there any method which check file existence – zen29d Dec 04 '19 at 18:52
  • The current working directory is not the directory containing the script; it's the current working directory when you run `python`. – chepner Dec 04 '19 at 20:17
  • @chepner, then how fix this, I want script to consider the directory where it is, not from where is run – zen29d Dec 04 '19 at 20:45

5 Answers5

1

thanks, everyone, finally I found the solution, never thought that would be easy.... just change the working directory and voila its work   

import os
...
script_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_path)
...
...
zen29d
  • 61
  • 7
0

Do a complete path, the tilda

~

specifies from where you "are right now"

to correctly specify it do the complete path. Easiest way to do this is go to file explorer, right click on the file, and press copy path. This should get you the complete path to the file which can be specified anywhere.

Please let me know if this helped!

Noah
  • 430
  • 1
  • 4
  • 21
  • Tilde means "relative to home directory", not "relative to where I am right now". – John Gordon Dec 04 '19 at 18:27
  • I run it from terminal, so specifying path every time is not possible. Complete path not suitable idea bcoz need to change directory sometimes. – zen29d Dec 04 '19 at 18:38
0

well, if you do not know the complete path, this is much more difficult IMHO. I don't have any good, pythonic idea to do that!

To search for the file within your whole PC, use subprocess module and execute "find" command on linux (you're on linux, right?), catch the output, and ask if your file is there:

import subprocess

file_name = "test.txt"

sp = subprocess.Popen(["find", '/', "-name", file_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = sp.communicate()

found = False
for line in output:
    if file_name.encode() in line:
        found = True

print("Found:", found)

NOTE: to delimit the search replace "/" by the parent folder you expect the file to be in.

EDIT: On windows, though I could not test it, the command would be: "dir /s /p hello.txt", so the subprocess call would look like this: sp = subprocess.Popen(["cmd", "/c", 'dir', '/s', '/p', 'Links'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Kalma
  • 111
  • 2
  • 15
0

In this case you need to search the file after walking through the directories and reading the contents. You might consider os.scandir() to walk through the directories [python 3.5]. https://www.python.org/dev/peps/pep-0471/

Sample:

def find_file(path: str) -> str:
    for entry in scandir(path):
        if entry.is_file() and entry.name == 'token.pickle':
            return_path = f'{path}\{entry.name}'
            yield return_path
        elif entry.is_dir():
            yield from find_file(entry.path)

if __name__ == '__main__':
    for path in find_file('.'):
        with open(path, 'rb') as token:
            creds = pickle.load(token)
partha biswas
  • 204
  • 1
  • 7
0

I see you already post an answer to your own question here

Anyway, I wanted to advice you there's no need to use os.chdir() for the purpose here really, simply do it like this:

# the real case

path_to_your_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),"token.pickle")

if os.path.exists(path_to_your_file):
    with open(path_to_your_file, 'rb') as token:
        ...

P.S. If you're wondering, there's several good reason to prefer using os.path.join() over manual string concatenation, the main one being it makes your coding platform independent in the first place

danicotra
  • 1,333
  • 2
  • 15
  • 34