问题
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