在python中的函数中将Windows路径转换为pathlib.WindowsPath

问题描述

为清楚起见而编辑

我需要能够直接从文件资源管理器中将Windows路径直接复制并粘贴到将其转换为pathlib.WindowsPath()对象的函数中。

例如:我想要的是类似的东西。

def my_function(my_directory):
    my_directory = pathlib.WindowsPath(my_directory) #this is the important bit 
    files = [e for e in my_directory.itirdir()]
    return(files)

new_list = my_function('C:\Users\user.name\new_project\data')

print(new_list[0])

OUT[1] 'C:\\Users\\user.name\\new_project\\data\\data_set_1'

尝试此操作时出现错误

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (<string>,line 1)

现在,我知道这是由于我传递给函数的Windows路径中的字符串中的\n,并且如果我以r'C:\Users\user.name\new_project\data'的形式传递,则此问题将得到解决。这不是解决我的问题的实用方法。有什么办法可以通过将Windows路径转换为函数中的原始字符串 解决此问题?

我尝试过:

def my_function(my_directory):
    input = fr'{my_directory}'# converting string to raw string
    path = pathlib.WindowsPath(input)
    files = [e for e in path.itirdir()]
    return(files)

new_list = my_function('C:\Users\user.name\new_project\data')

print(new_list[0]

OUT[1] 'C:\\Users\\user.name\\new_project\\data\\data_set_1'

但没有喜悦。

任何帮助将不胜感激。

解决方法

尝试一下。在目录中添加双反斜杠,以便python不会将单个反斜杠解释为转义符

new_list = my_function('C:\\Users\\user.name\\new_project\\data')
,

您可以通过简单地将其转换为“原始”字符串来保持简单。这可以在可以使用任何其他路径的任何地方使用。 (os.path、Pathlib 等)

mypath = r'C:\Users\user.name\new_project\data' 打印('我的路径是 =',我的路径)

输出: 路径是 = C:\Users\user.name\new_project\data

,

我通过使用 .encode('unicode escape')

解决了这个问题

例如:

from pandas import path

def input_to_path():
    user_input = input('Please copy and paste the folder address')
    user_input.encode('unicode escape')
    p = Path(user_input)
    return(p)