# -*- coding: utf-8 -*-
"""
Created on Tue Jul 13 16:09:34 2021
@author: kang
"""
def count_words(filename):
try:
with open(filename,'r') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = ['D:\\study_soft\\Anaconda\\workstation\\a.txt']
count_words(filenames)
这是我的代码段,是为了分析a.txt里面有多少个词,结果运行出现了以下的错误:
runcell(0, 'D:/study_soft/Anaconda/workstation/1.分析文本.py')
Traceback (most recent call last):
File "D:\study_soft\Anaconda\workstation\1.分析文本.py", line 21, in <module>
count_words(filenames)
File "D:\study_soft\Anaconda\workstation\1.分析文本.py", line 10, in count_words
with open(filename,'r') as f_obj:
TypeError: expected str, bytes or os.PathLike object, not list
重点就在最后一句:
TypeError: expected str, bytes or os.PathLike object, not list
问题解决:
1. 使用绝对路径的时候,注意要用两个单斜杠;
2. 写文件的名称的时候,不能加[ ]。(本人的代码中就是这个问题,加了[ ])
将[ ]去掉,即可
def count_words(filename):
try:
with open(filename,'r') as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
# Count approximate number of words in the file.
words = contents.split()
num_words = len(words)
print("The file " + filename + " has about " + str(num_words) + " words.")
filenames = 'D:\\study_soft\\Anaconda\\workstation\\a.txt'
count_words(filenames)
运行结果:
runcell(0, 'D:/study_soft/Anaconda/workstation/1.分析文本.py')
The file D:\study_soft\Anaconda\workstation\a.txt has about 1 words.
至此,问题解决!!!
更多推荐