【发布时间】: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