异常:"unicode"对象没有属性"readlines" [英] Exception : 'unicode' object has no attribute 'readlines'

查看:58
本文介绍了异常:"unicode"对象没有属性"readlines"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一个csv文件路径传递给此函数.

I passing a csv file path into this function.

def validateCSV(filename):
    with open(filename, 'rb') as file:
        print type(filename)
        if not filename.readlines(): 
            print 'empty file'
        else:
            reader = csv.reader(file)
            for row in reader:
                print row
    file.close()

但是当我运行它时,我得到了一个错误

but when I run this I got an error

'unicode'对象没有属性'readlines'

'unicode' object has no attribute 'readlines'

但是当我检查csv文件的类型时,它是unicode.所以我知道他们需要一个文件对象,那么我怎样才能将unicode转换为文件对象.然后我尝试了这个,

but when I check the type of the csv file it is unicode. So I understood that they need a file object.So how can I convert unicode to file object. Then i tried this,

filename = filename.encode("utf-8")

然后它的类型变为字符串并显示另一个错误.

then its type becomes string and shows another error.

'str'对象没有属性'readlines'

'str' object has no attribute 'readlines'

请帮助我.谢谢.

推荐答案

您正在从文件名(肯定是Unicode对象)中调用 readline()方法.如果要检查文件是否为空,则可以使用 next 函数简单地获取第一行,并使用try-except语句将其包装起来:

You are calling the readline() method from your file name which is certainly a Unicode object. If you want to check if your file is empty or not you can simply get the first row using next function and wrap it with a try-except statement:

def validateCSV(filename):
    with open(filename, 'rb') as f:
          reader = csv.reader(f)
          try:
              first_row = next(reader)   
          except StopIteration:
              print('empty file')
              return
          else:
              print(first_row)
              for row in reader:
                  print row

还请注意,当使用 with 上下文管理器时,不需要关闭文件对象.它将自动在块末尾关闭文件.

Also note that you don't need to close your file object when you are using with context manager. It will close the file at the end of the block automatically.

这篇关于异常:"unicode"对象没有属性"readlines"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆