简体   繁体   English

python csv换行

[英]python csv new line

iam using this code to convert db table to csv file, it is converting in to csv but instead of new line / line breck its using double quotes , can someone help me iam使用此代码将db表转换为csv文件,正在将其转换为csv,但使用双引号代替了新的行/行breck,有人可以帮我吗

import MySQLdb
import csv
conn = MySQLdb.connect(user='root',  db='users', host='localhost')
cursor = conn.cursor()
cursor.execute('SELECT * FROM users.newusers')
ver = cursor.fetchall()
ver1 = []
for ve in ver:
    ve = str(ve).replace("', '","|").replace(", '","|").replace(","," ").replace("  "," ").replace("|",",")
    ver1.append(ve)
print ver1
csv_file = open('filename', 'wb')
writer = csv.writer(csv_file)
writer.writerow(ver1)       csv_file.close()                                                                                

current output 电流输出

"(114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes')","(115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes')"

expected out 预期出来

 114L,New,9180971675,Ravi Raju,RAJRAVI,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.0.1,no,yes


 115L,New,9180971676,Rajendran Mohan,rajemoh,National,#N.A,No,No,No,#N.A,OS40,005056BB0803,192.168.10.10,no,yes

SQL queries will return results to you in a list of tuples from fetchall() . SQL查询将从fetchall()的元组列表中返回结果。 In your current approach, you iterate through this list but call str() on each tuple, thereby converting the whole tuple to its string representation. 在当前方法中,您遍历此列表,但在每个元组上调用str() ,从而将整个元组转换为其字符串表示形式。

Instead, you could use a list comprehension on each tuple both to get it into a nested list format and apply your replace() operations. 相反,您可以在每个元组上使用列表推导,既可以将其转换为嵌套列表格式,也可以应用replace()操作。

for ve in ver:
    ver1.append([str(item).replace(<something>) for item in ve])

In the final step you use csv.writerow() which is designed to be used within a for loop. 在最后一步中,您将使用csv.writerow() ,该csv.writerow()设计用于for循环。 If your list is nested in the form [[row1], [row2]] then you can just change this to writerow s . 如果您的列表以[[row1], [row2]]的形式嵌套,则可以将其更改为writerow s Also, it's best practice to use the context manager with to handle files as this will automatically close the file once the operation is completed. 此外,它使用上下文管理最佳实践with处理文件,一旦操作完成,这将自动关闭文件。

with open('filename.csv', 'wb') as csv_file:
     writer = csv.writer(csv_file)
     writer.writerows(ver1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM