The path is passed to the function of the form D: \ folder \ file.txt. The problem is that the os.path.dirname (src) function works correctly only with double slash \ or single backslash paths.

It seems that you just need to make a replacement, but my replacement leads to some kind of abcadabra src path = D: /ProjectB4rchdata♀older1.ini

I can not understand where these special characters come from. Can the os.path.dirname function work incorrectly?

Here is the code itself

# -*- coding: utf8 -*- import os import ntpath import shutil dst_sav = "D:\\savorsk\\" #.replace("\\","/") def copyfilestofolder(src): src = src.replace("\\","/") print "src path = %s" %src dbfilepath = os.path.dirname(src) print dbfilepath copyfilestofolder("D:\Project\2014\archdata\folder1.ini") 

I just need to somehow get into the dbfilepath variable the path to the directory in which the file lies, but nothing happens.

Tell me the solution.

    2 answers 2

    The double slash in the string is not 2 characters at all. I.e

     >>> print '\\' \ 

    and you do not need to replace 2 slashes by 1.

    And you need to transfer the source file path as

     "D:\\Project\\2014\\archdata\\folder1.ini" 

    Since \ P, \ 2, \ a, \ f - in the line will be interpreted as special characters

    • But how to do it? .replace ("two slashes", "four slashes")? * Parser buggy replaced with words - Dmitry Bubnenkov
    • Replace nothing at all. You write 2 slashes, the python thinks that it is 1. That's all. - LinnTroll

    In general, it is best to use the r specifier for the string, which means - the string is entered in the raw format (you do not need to escape anything). Equally well suited for both regular expressions and paths:

      r"D:\Project\2014\archdata\folder1.ini" 

    qualifier can be set in upper case

    The advantages of such a solution are that readability does not fall compared with shielding.