【问题标题】:Python normalized pathname with a special case具有特殊情况的 Python 规范化路径名
【发布时间】:2013-04-05 13:07:48
【问题描述】:

考虑以下示例

#junk path ending with a test file
test = "C:\\test1/test2\test3.txt"

import osos.path.abspath in可以规范化路径名

test_norm = os.path.abspath(test)
print test_norm    
C:\\test1\\test2\test3.txt'

如果我用os.path.split 分割路径名,我会遇到以下问题

os.path.split(test_norm)
('C:\\test1', 'test2\test3.txt')

而不是

C:\\test1\\test2 and test3.txt

这个问题源于用户键入input_raw 一个目录作为示例。我可以通过raw_input 避免这种情况吗?

【问题讨论】:

  • 测试最初是如何设置的?他们输入了什么,你在设置什么?

标签: python debugging path directory normalization


【解决方案1】:

简单:'\t' 是一个制表符。您需要使用'C:\\test1\\test2\\test3.txt'r'C:\test1\test2\test3.txt'

【讨论】:

  • 嘿@micheael。如果有人错在我的软件中写了 input_raw 作为例子。我怎样才能避免这种情况?
  • @Gianni: raw_input 不处理转义。如果有人在提示符下键入\t\r\n,您将得到字符串"\\t\\r\\n"(或者,等效且更易读的r"\t\r\n")。
  • @Michael - 您可以使用os.path.isfile(what_the_user_input) 查看文件是否存在并警告用户。
【解决方案2】:

你没有转义最后的斜线,所以 python 认为你想要一个制表符 (\t) 而不是分隔符 (\\)。 test = "C:\\test1/test2\test3.txt" 应该是 test = "C:\\test1/test2\\test3.txt"

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    • 2018-03-31
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多