【问题标题】:open: invalid mode or filename打开:无效的模式或文件名
【发布时间】:2015-05-15 05:37:47
【问题描述】:

这是字数统计程序。怎样才能变得更简单?

import re
from collections import Counter

with open('C:\Data\test.txt') as f:
passage = f.read()

words = re.findall(r'\w+', passage)

cap_words = [word.upper() for word in words]

word_counts = Counter(cap_words)

不断收到此错误消息:

Traceback (most recent call last):
File "C:/Python27/wordcount", line 4, in <module>
with open('C:\Data\test.txt') as f:
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Data\test.txt'

【问题讨论】:

    标签: python file word-count


    【解决方案1】:

    使用原始字符串或使用\ 转义每个\。这是必需的,因为没有它 '\t' 将被转换为制表符空间:

    r'C:\Data\test.txt'
    

    例子:

    >>> print 'C:\Data\test.txt'
    C:\Data est.txt                 #\t is converted to tab
    >>> print r'C:\Data\test.txt'   
    C:\Data\test.txt                #here it is fine
    
    >>> print 'C:\\Data\\test.txt'  #same as raw string, but manual escaping
    C:\Data\test.txt
    

    【讨论】:

    • 或者他可以直接使用'C:\\Data\\test.txt'
    • 我尝试使用双反斜杠,但没有出现错误消息。但是,当我实际运行程序时,什么都没有出现,它只是说“重新启动”,这是为什么?
    • @user2554477 你没有在你的程序中打印任何东西,你希望它打印什么?
    • @user2554477 看看我之前的解决方案:stackoverflow.com/a/17493530/846892
    • 我明白了,抱歉我是初学者
    猜你喜欢
    • 1970-01-01
    • 2020-07-11
    • 2012-12-24
    • 1970-01-01
    • 2023-01-19
    • 2017-10-08
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    相关资源
    最近更新 更多