Python: AttributeError: 'NoneType' 对象没有属性 'rfind'

标签 python file-extension

我正在尝试使用 os.path.splitext 确定文件扩展名

这是我的代码:

for emailid in msgs:
    typ, s = mail.fetch(emailid, "(RFC822)")
    m = email.message_from_string(s[0][1])
    result = re.findall(pattern,str)
    if result:     
        for part in m.walk():
            filename = part.get_filename()
            if filename:
                extension = os.path.splitext(fileName)
                if extension[1][1:] == 'csv':      
                    ### Process into a dataframe
                    df = pd.read_csv(StringIO(filename))

这是从 IPython 中读出的错误:

#### Begin error Message #####

    AttributeError                            Traceback (most recent call last)
<ipython-input-83-71fabd157c43> in <module>()
     40             if filename:
     41                 print type(filename)
---> 42                 extension = os.path.splitext(fileName)
     43                 if extension[1][1:] == 'csv':
     44                     ### Process into a dataframe

C:\Anaconda2\lib\ntpath.pyc in splitext(p)
    198 
    199 def splitext(p):
--> 200     return genericpath._splitext(p, sep, altsep, extsep)
    201 splitext.__doc__ = genericpath._splitext.__doc__
    202 

C:\Anaconda2\lib\genericpath.pyc in _splitext(p, sep, altsep, extsep)
     97     leading dots.  Returns "(root, ext)"; ext may be empty."""
     98 
---> 99     sepIndex = p.rfind(sep)
    100     if altsep:
    101         altsepIndex = p.rfind(altsep)

AttributeError: 'NoneType' object has no attribute 'rfind'

#### End Error message #####

NoneType 应该意味着我没有传递任何东西,当我打印类型(文件名)时,我得到:

如何传递文件以便确定扩展名然后创建数据框?我需要保存到磁盘吗

这将用于解析脚本,该脚本会定期通过电子邮件发送给它的 csv,因此由正则表达式确定要遵循的规则。

最佳答案

extension = os.path.splitext(fileName) 中,您使用的是变量 fileName,而不是 filename。 Python 区分大小写,因此这些是不同的变量。显然,fileName 在别处被设置为 None,将该实例更改为 filename 应该可以修复此错误。

关于Python: AttributeError: 'NoneType' 对象没有属性 'rfind',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37716326/

相关文章:

python - 凹面掩模到凸面

python - 如何使用 spacy nlp 查找专有名词

python - 如何修复 vscode 中的 'jupyter notebook server failed to launch in time'?

path - 从 Rust 中的给定路径中惯用地提取文件扩展名

c++ - 如何在Windows 8中设置关联?

python - 将值附加到 Pandas 系列

python - matplotlib 从轴获取可映射的颜色条

c - 编辑字符串时出现段错误?

c - 如何在压缩前获取文件的类型

c# - SaveFileDialog AddExtension 无法按预期工作