Python I/O error: How do I fix this program for file paths with whitespace?

Python I/O error: How do I fix this program for file paths with whitespace?

当运行代码。

file_path = raw_input("Drag the text file here: ")
file_path = file_path.strip()
file_handle = open(file_path, 'r')
for line in file_handle:
    print line

输出:

Drag the text file here: /Users/user_name/Desktop/white\ space/text.txt 
Traceback (most recent call last):
  File "desktop/test.py", line 3, in <module>
    file_handle = open(file_path, 'r')
IOError: [Errno 2] No such file or directory: '/Users/user_name/Desktop/white\ space/text.txt'

对于任何没有空格的路径名,该程序都可以正常运行。

立即解决方法是删除转义的 '\' 个字符,file_path.strip().replace('\', '')

这应该 return /Users/user_name/Desktop/white space/text.txt 这是您可以使用的有效路径。

查看 os.path 以了解处理路径名的方法。