Replace slashes "" in os.getcwd()

Question:

I am trying to get the current working directory and add it to a file path with os.getcwd. Because windows uses forward slashes in the directory path, I need to change all of these slashes to back slashes for it to work in python.

What I’ve tried:

import os

old = getcwd()

new = old.replace("", "/")

file_path = (new + "folder/filename")

print(file_path

The above is throwing an error of SyntaxError: EOL while scanning string literal

Asked By: patriciajlim

||

Answers:

Because windows uses forward slashes in the directory path

It doesn’t — it uses backslashes (but it also accepts forward slashes).

This works, regardless of operating system:1

import os

file_path = os.path.join(os.getcwd(), 'folder', 'filename')
# also works:
# file_path = os.path.join(os.getcwd(), 'folder/filename')

… but the specific error you’re getting is because you’re attempting to use an un-escaped backslash in a Python string. Since backslashes in strings have a special meaning, its usage needs to be escaped: use "\" instead of "". But as mentioned above, that’s irrelevant here (and 99% of the time when working with paths).


1 A cleaner approach would be via pathlib, which uses properly typed objects to encode paths, instead of strings:

import pathlib

file_path = pathlib.Path('.').absolute() / 'folder' / 'filename'
Answered By: Konrad Rudolph
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.