Skip to main content
 首页 » 编程设计

python之使用unittest django测试存储在内存中的csv文件

2024年10月24日46kuangbin

尝试写入 csv 文件时出现错误。这是我的两个脚本:

任务.py

def get_data(): 
 
          customer = Customer.objects.all() 
          csvfile = StringIO.StringIO() 
          csvwriter = csv.writer(csvfile) 
 
          for i in customers: 
              csvwriter.writerow([str(i.phone_number)]) 
 
          return csvfile 

在测试.py中:

    with open(get_data().getvalue(), 'rb') as myfile: 
        data = [row for row in csv.reader(myfile.read().splitlines())] 
        print data 

这是错误:

IOError: [Errno 2] No such file or directory: '999999999\r\n' 

其中 '999999999' 是应该写入文件的内容。

我该如何解决这个问题?

请您参考如下方法:

您的 get_data() 函数不返回文件,而是返回一个 StringIO 对象。你不需要open()它,你可以像这样阅读它:

myfile = get_data().getvalue() 
data = [row for row in csv.reader(myfile.splitlines())] 
print data