gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:54 25 4
gpt4 key购买 nike

尝试写入 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

关于python - 使用unittest django测试存储在内存中的csv文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com