Exception : 'unicode' object has no attribute 'readlines' [closed]

情到浓时终转凉″ 提交于 2019-12-19 12:03:50

问题


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' object has no attribute 'readlines'

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' object has no attribute 'readlines'

Please help me.Thanks in advance.


回答1:


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

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.




回答2:


Refer to line :- if not filename.readlines(): readlines() is a method present on file type object and not on string object.

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


来源:https://stackoverflow.com/questions/42560796/exception-unicode-object-has-no-attribute-readlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!