python - 打开: invalid mode or filename

标签 python file word-count

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

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'

最佳答案

使用原始字符串或使用 \ 转义每个 \。这是必需的,因为没有它 '\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

关于python - 打开: invalid mode or filename,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17493879/

相关文章:

Python 3.5 : slice vs islice vs alternatives? 效率对比

php - 使用 vfsStream 测试 move_uploaded_file 和 is_uploaded_file

python - Scrapy不处理Xpath和CSS选择器中的TBODY

c++ - 如何获取临时/右值的地址进行复制?

java - java中如何将文件放入数组中

amazon-web-services - AWS Hadoop MapReduce-平均字数

python - 以最快的方式计算python中的重复单词

console - openoffice 可以从控制台计算单词吗?

python - 终端命令未完成

python - 模式的惰性匹配