【问题标题】:How to handle windows path in Python?如何在 Python 中处理 windows 路径?
【发布时间】:2021-09-18 20:28:22
【问题描述】:

代码的要求是我必须在控制台中从用户那里获取文件路径并对该文件执行一些操作。用户可以以 windows 样式或 mac 样式给出路径。对于 mac 或 Linux,路径代码工作正常,但对于 windows 路径,它给出一个错误(因为)如何处理这个错误,因为我不能在其中使用 'r' 字符串,因为它来自用户。

user_path = input('give text file path: ') 
file = open(user_path, 'r') 
words = file.read().split() 
print('total number of words: ', len(words))

如果我提供路径:C:\desktop\file.txt 它给出错误

【问题讨论】:

  • 请举一些例子。
  • 请发布您的代码。
  • user_path = input('给出文本文件路径:') file = open(user_path, 'r') words = file.read().split() print('总字数:' , len(words)) 如果我提供路径:C:\desktop\file.txt
  • 使用os.path.abspath(user_path)将其转换为绝对路径,然后使用os.path.exists(user_path)检查它是否存在,如果为真则打开文件,否则在文件不存在的情况下将抛出异常。
  • import os path = input("path: ") path_abs = os.path.abspath(path) print(path_abs) file = open(path_abs, 'r')

标签: python path operating-system pathlib


【解决方案1】:

使用C:\\desktop\\file.txt 代替C:\desktop\file.txt

【讨论】:

    【解决方案2】:

    错误是由于 python 将 'C:\desktop\file.txt' 中的 '\f' 识别为换页符转义序列。

    在提供输入时使用正斜杠“/”而不是反斜杠可以简单地解决。

    【讨论】:

    • 但是用户可以输入任何输入,我们可以处理这种情况吗?例如,在 Windows 中,如果我们复制为路径,它会在路径中使用 '\' 复制
    • 使用以下代码: import pathlib path = pathlib.Path(input()) 我试过这个,它处理斜线(向前和向后)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2011-04-19
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 2022-01-22
    • 2021-05-19
    相关资源
    最近更新 更多