python导出数据找不到csv_【记录】使用Python读取/导出(写入)CSV文件
想要用python處理csv文件。
去查了下,python中本身就自帶csv模塊。
然后參考在線手冊:
去試試。
【用python生成csv】
1. 按照手冊的例子,試了試:import csv
with open('eggs.csv', 'wb') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
然后生成的文件,原始數據為:Spam Spam Spam Spam Spam |Baked Beans|
Spam |Lovely Spam| |Wonderful Spam|
然后用excel打開結果為:
很明顯,不是想要的結果,因為只是一列,實際應該是6列才對。
2. 然后折騰了一下之后,參考手冊的說明:csv.writer(csvfile[, dialect=’excel’][, fmtparam])Return a writer object responsible for converting the user’s data into delimited strings on the given file-like object. csvfile can be any object with a write() method. If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference. An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparam keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string. While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written.
去改為:import csv
with open('eggs.csv', 'wb') as csvfile:
#spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter = csv.writer(csvfile, dialect='excel')
spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
然后就可以顯示正常了:
去看了下源碼為:Spam,Spam,Spam,Spam,Spam,Baked Beans
Spam,Lovely Spam,Wonderful Spam
【總結】
使用python的csv生成excel所兼容的csv文件的話,主要就是創建writer時的參數時要有dialect=’excel’,就可以了。
【用Python讀取從excel導出的csv文件】
再去嘗試用python處理,從excel 2010導出的一個csv文件:
參考手冊的代碼,使用如下代碼:import csv
with open('excel_2010_ms-dos.csv', 'rb') as csvfile:
#spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
spamreader = csv.reader(csvfile, dialect='excel')
for row in spamreader:
print ', '.join(row)
去測試,然后是可以正常打印出結果的:D:\tmp\tmp_dev_root\python\test_csv>test_csv.py
a1, b1, c1, d1
a2, , c2,
, b3, ,
【總結】
只要指定了對應的dialect=’excel’,也是可以很方便的使用python的csv處理excel所導出的ms-dos的csv文件的。
總結
以上是生活随笔為你收集整理的python导出数据找不到csv_【记录】使用Python读取/导出(写入)CSV文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 协议森林02 小喇叭开始广播 (以太网与
- 下一篇: 212