0

I'm trying to open a file like this:

with open(str(script_path) + '\\description.xml', 'w+') as file:

where script_path is equal to this:

script_path = os.path.dirname(os.path.realpath(__file__)) + '\\.tmp')

When I run this I get an error that there is no such file or directory because when it tries to open the file it sees the whole path as a string, including the escape strings. Is there any way around this? Obviously .replace() won't work here as it won't replace the escape string. Hoping there is a clever way to do this within the os module?

3
  • Why are there two backslashes? If description.xml is in the same directory as the script, the relativr path is just description.xml Commented Jul 3, 2020 at 10:06
  • I think I did this so it would be in the tmp folder, although I guess I could just use '.tmp/description.xml' Commented Jul 3, 2020 at 10:12
  • I recommend using os.path.join to create a path instead of string concatenation. This might help avoiding this problem. Commented Jul 3, 2020 at 11:31

1 Answer 1

1

Not really sure why you're adding two backslashes. You can simply create the path using a single forward slash (Linux based) or backslash (win). Something like this:

script_path = os.path.dirname(os.path.realpath(__file__)) + '/tmp/description.xml'

However, better way to achieve this would be to use os.path.join as suggested by nomansland008.

>>> import os

>>> parent_dir = "xyz"
>>> dir = "foo"
>>> file_name = "bar.txt"
>>> os.path.join(parent_dir, dir, file_name)
'xyz/foo/bar.txt'

You won't have to bother about whether the string has slash(or not). It will be taken care by join. In your case it can simply be:

os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp', 'description.xml')

Should work, provided the files and directories exist.

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.