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 - 展开 PySpark DataFrame 的数组列

php - 如何从 PHP 中的目录获取 X 个最新文件?

javascript - 如何将 Base64 String 转换为 javascript 文件对象,就像从文件输入表单一样?

java - 使用 Apache Tika 提取文本,然后在删除停用词后获取频繁出现的单词

python - 有效计算python中的词频

python - 比较嵌套列表 Python

python - 异常是 : unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

python - Python 中 Pandas 的快速取子集

python - 使用 Python 将列表写入文件,使用换行符

c - C程序中的字数统计