首页 > 解决方案 > 路径名格式 - Windows - Python

问题描述

我正在编写一个获取文件路径并读取它的代码。代码是,

import sys
import os

user_input = input("Enter the path of your file: ")

assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)

但是,我在一台 Windows 机器上,其中的路径名带有一个\,比如,C:\your\path\and\file.xlsx

每次在提示符下输入文件名,都需要手动全部替换\/然后运行代码。

是否有解决方案可以让我输入C:\your\path\and\file.xlsx,但代码将其视为,C:/your/path/and/file.xlsx

问候。

标签: python

解决方案


像这样使用内置的python pathlib

from pathlib import Path

# No matter what slash you use in the input path
# I used Raw-Prefix 'r' here because \t would otherwise be interpreted as tab
path_a = Path(r"C:\Temp\test.txt)
path_b = Path(r"C:\Temp/test.txt)
path_c = Path(r"C:/Temp/test.txt)
path_d = Path(r"C:\\Temp\\test.txt)

print(path_a, path_b, path_c, path_d)
# all Paths will be the same:
# out >> C:\Temp\test.txt C:\Temp\test.txt C:\Temp\test.txt C:\Temp\test.txt

此外,您还可以像这样轻松扩展给定的路径:

path_e = Path("C:\Temp")
extended_path = path_e / "Test"
print(extended_path)
# out >> C:\Temp\Test

所以在你的情况下,只需这样做:

import sys
import os

from pathlib import Path

user_input = input("Enter the path of your file: ")

file_path = Path(user_input)

if not os.path.exists(file_input):
     print("I did not find the file at, " + str(file_path))

推荐阅读