Py学习  »  Python

使用python 3中的换行符将字符串写入csv

ke0crj • 6 年前 • 3048 次点击  

在python 3.7中工作。

我目前正在从一个API(Qualys的API,获取一个报告)中提取特定的数据。它返回一个字符串,其中所有报表数据都是csv格式,每行都用\r\n'转义符指定。

(即“foo、bar、stuff \r\n、more stuff、data、report等\r\n等)

我遇到的问题是把这个字符串正确地写到一个csv文件中。在Excel中查看时,我尝试过的每一个代码迭代都会逐个单元格地写入数据,并将其附加到字符串中的任何位置\r\n而不是新行中。

(即foo bar staff \r\n more staff data report \r\n etc etc \r\n)

我只是在从2切换到3,所以我几乎肯定这是一个语法错误,或者是一个理解python 3如何处理新行分隔符的错误,或者是沿着这些行的错误,但是即使在审阅了文档、这里和博客文章之后,我也不能完全理解它,或者我总是缺少一些东西。

当前代码:

def dl_report(id, title):
    data = {'action': 'fetch', 'id': id}
    res = a.request('/api/2.0/fo/report/', data=data)
    print(type(res)) #returns string

    #input('pause')
    f_csv = open(title,'w', newline='\r\n')
    f_csv.write(res)
    f_csv.close

但我也尝试过:

with open(title, 'w', newline='\r\n') as f:
    writer = csv.writer(f,<tried encoding here, no luck>)
    writer.writerows(res)

#anyone else looking at this, this didn't work because of the difference 
#between writerow() and writerows()

我还尝试了各种方法来声明新行,例如:

newline=''
newline='\n'
etc...

以及沿着这些线的各种其他迭代。任何建议或指导,或…在这一点上,任何事情都是了不起的。

编辑:

好吧,我一直在努力,这有点管用:

def dl_report(id, title):
data = {'action': 'fetch', 'id': id}
res = a.request('/api/2.0/fo/report/', data=data)
print(type(res)) #returns string

reader = csv.reader(res.split(r'\r\n'), delimiter=',')

with open(title, 'w') as outfile:
    writer = csv.writer(outfile, delimiter= '\n')
    writer.writerow(reader)

但它很难看,并且确实会在输出csv中产生错误(某些行(小于1%)不会解析为csv行,可能是某个位置的格式错误….),但更令人关注的是,当数据中出现一个“\”时,它的工作会很不稳定。

我真的会对一个有效的解决方案感兴趣…更好?更多的蟒蛇?更始终如一的方法是…

有什么想法吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30658
 
3048 次点击  
文章 [ 4 ]  |  最新文章 6 年前