1

I am using python on mac and would like to open a pdf file that is present in different directory than the directory my main python code is running. I tried different options but there is always an error saying file doesn't exist even when the file is present or [Error no. 2] file cannot be opened. Here is the code that I use:

helpFile = os.path.abspath('~/help/help.pdf')
self.help_btn = tk.Button(self.help_frm, text="Help!", width=8, command = lambda: os.system("open "+helpFile))

could some one help please.

1
  • That code has a lot going on - TkInter, lambda, os.path.abspath, etc. I would simplify it to code that simply tries to open and read a file. That way, you can ask the question more simply, and also it'll be easy to spot the issue. Commented May 31, 2015 at 22:38

1 Answer 1

1

abspath does not expand ~ into the user's home directory, it just calculates the absolute path of a file based on its path relative to the current working directory.

From the docs, it is equivalent to:

normpath(join(os.getcwd(), path))

So in your code, helpFile is being set to "/path/to/cwd/~/help/help.pdf"

To expand ~, use os.path.expanduser.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.