debug之csv文件打开报错

遇到的提示错误:_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?

错误code如下:

 1 import csv
 2 import sys
 3 
 4 input_file = sys.argv[1]
 5 output_file = sys.argv[2]
 6 
 7 with open(input_file, 'r') as csv_in_file:   
 8     with open(output_file, 'w') as csv_out_file:
 9         filereader = csv.reader(csv_in_file)      
10         filewriter = csv.writer(csv_out_file)
11         header = next(filereader)
12 
13         #print header
14 
15         filewriter.writerow(header)
16         for row_list in filereader:
17            #print row_list
18             supplier = str(row_list[0]).strip()
19             cost = str(row_list[3]).strip("$").replace(',', '')
20             if supplier == 'Supplier X' or float(cost)>600.0:
21                 filewriter.writerow(row_list)

解决方法:

将上述代码第7行写成 with open(input_file, 'rU') as csv_in_file: 后解决

主要是打开文件的模式不正确

'U'       universal newline mode (deprecated)——在python3中已经弃用

详见:http://www.runoob.com/python/python-func-open.html

https://blog.csdn.net/u010105645/article/details/78808779

猜你喜欢

转载自www.cnblogs.com/slhs/p/9642178.html
今日推荐