我想要读取并将数据从CSV保存到列表并发送到服务器。我的算法: 1.打开CSV文件 2.检查CSV文件中的数据,如果在CSV文件中没有数据我不想保存到列表但如果在CSv中有数据,则数据将保存到列表并发送到服务器。 3.读取后删除数据
我在步骤2和3中遇到问题,因为没有数据我的系统将空白列表发送到服务器。 我使用python 2.7并且有我的代码: `def readFile(self): 尝试: print“open”+ self.filename f = open(self.filename) csv_f = csv.reader(f)
except IOError:
print 'cannot open file'
else:
## Read the first line
print "file opened " + self.filename
## If the file is not empty keep reading line one at a time
## till the file is empty
for row in csv_f:
Data.append(row)
del (row)
f.close()
return Data
你能帮助我吗?
答案 0 :(得分:0)
是因为函数返回None,因为没有任何附加到Data的数据,那么你是否将None发送给服务器进行保存?
答案 1 :(得分:0)
您需要先检查文件是否为空。即如果包含或不包含行,则使用csv模块导入csv文件并将其转换为字典并检查它是否为空...如果为空则返回无其他返回数据。检查以下代码。
with open(file, "rb") as csv_f:
csvdict = csv.DictReader(csv_f)
rows = False
for line in csvdict:
rows = True
if not rows:
return None
else:
for row in csv_f:
Data.append(row)
del (row)
f.close()
return Data
答案 2 :(得分:0)
class WorkCSV(object):
def __init__(self, filename):
self.filename = filename
def readFile(self):
try:
with open(self.filename) as fd:
print "open " + self.filename
row_items = [row for row in fd.xreadlines()]
print "opened " + self.filename
if row_items:
print row_items
return row_items
else:
print "file empty"
return None
except IOError as err:
print "cannot open file"