【问题标题】:Python I/O error: How do I fix this program for file paths with whitespace?Python I/O 错误:如何为带有空格的文件路径修复此程序?
【发布时间】:2016-06-10 20:17:01
【问题描述】:

运行代码时。

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'

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

【问题讨论】:

    标签: python io whitespace filepath


    【解决方案1】:

    立即修复将删除转义的'\\' 字符,file_path.strip().replace('\\', '')

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

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

    【讨论】:

    • 这种方法的问题是有些字符不能简单地通过删除``来取消转义。但由于这些字符不太可能是文件名的一部分,所以这可能有效。
    • @MarkRansom,你是最正确的。我应该在回复中强调立即
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多