Python运行错误TypeError: expected str, bytes or os.PathLike object, not list的解决方法

# -*- 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.

至此,问题解决!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaoxiaoqin@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值