python - 路径名格式 - 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 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))
推荐阅读
- javascript - 函数没有返回任何值
- css - Chrome 不尊重 display: inline on flexbox children
- wordpress - 革命滑块激活问题
- json - 如何删除 JSON 数组中的“/”并从 JSON 数组中获取特定值?
- ruby-on-rails - Rails, Postgres, Distinct on and order by another column
- java - 为什么我不能使用嵌套的 IntList 创建对象?
- arrays - 如何在插座集合下禁用单个 UIButton(按下时)?
- python - Keras tf 后端预测批量大小为 1 的速度很慢
- testing - 测试 vim 脚本
- python - 变量作为python数组键但没有初始化或声明