toppic
当前位置: 首页> 奇幻小说> python_读取和写入csv

python_读取和写入csv

2020-06-20 07:56:44
bugs~~~解决方式1?!

首先,先上官方文档:
https://docs.python.org/3/library/csv.html


import csv
f = open('f://egg.csv', 'rb') # opens the csv file
try:
reader = csv.reader(f) # creates the reader object
   
for row in reader: # iterates the rows of the file in orders
       
print(row) # prints each row
finally:
f.close() # closing


And the error is:

    for row in reader:   # iterates the rows of the file in orders
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

'rb'改成'r'就好了。



Instead of this (and the rest):

f = open('Address Book.csv', 'rb')

Do this:

with open('Address Book.csv', 'r') as f:
    reader = csv.reader(f) 
    for row in reader:
        print(row)  
#写成这种形式更好

The context manager means you don't need that generic error handling, because it will automatically close the file on an error, or on exiting the context.


至此,还没有解决,为什么去掉“b”就可以了。“b”代表二进制形式。明日再说!



  1. csv是逗号分隔符格式,一般我们用的execl生成的格式是xls和xlsx 直接重命名为csv的话会报错:
    Error: line contains NULL byte

    insun解决方案:不要把后缀为xls的execl文件重命名直接为csv,可以Excel另存为csv,或者从库中导出,否则会出错。

  2. python中本身就自带csv模块,参考在线手册:http://docs.python.org/2/library/csv.html

  3. 参考:http://bugs.python.org/msg82661

    http://stackoverflow.com/questions/22132034/csv-error-iterator-should-return-strings-not-bytes-did-you-open-the-file-in

  4. 注释:

CSV全称为“Comma Separated Values”,是一种格式化的文件,由行和列组成,分隔符可以根据需要来变化。
如下面为一csv文件:

Title,Release Date,Director And Now For Something Completely Different,1971,Ian MacNaughton Monty Python And The Holy Grail,1975,Terry Gilliam and Terry Jones Monty Python's Life Of Brian,1979,Terry Jones Monty Python Live At The Hollywood Bowl,1982,Terry Hughes Monty Python's The Meaning Of Life,1983,Terry Jones

csv可以比较方便的在不同应用之间迁移数据。可以将数据批量导出为csv格式,然后倒入到其他应用程序中。很多应用中需要导出报表,也通常用csv格式导出,然后用Excel工具进行后续编辑。例如,一个用户可能需要交换信息,从一个以私有格式存储数据的数据库程序,到一个数据格式完全不同的电子表格。最可能的情况是,该数据库程序可以导出数据为“CSV”,然后被导出的CSV文件可以被电子表格程序导入。



友情链接