python操作csv文件
参考资料
需要读取操作的文件:test_data.csv
'name','age'
'tao','12'
'hong','13'
'明','15'
第一次读测试:
#encoding:utf-8
import csv
if __name__ == '__main__':
csv_file = csv.reader(open('test_data.csv','r'))
for line in csv_file:
print(line)
测试结果
D:\Anaconda\python.exe E:/projects/python/python_deoms/CSV-demo/CSV_Demo.py
Traceback (most recent call last):
File "E:/projects/python/python_deoms/CSV-demo/CSV_Demo.py", line 6, in <module>
for line in csv_file:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x8e in position 42: illegal multibyte sequence
我们可以看到主要的报错信息是编码错误,我们只需要解决的编码问题即可,详见第二次测试
第二次读测试: 添加了codes模块
#encoding:utf-8
import csv
import codecs
if __name__ == '__main__':
csv_file = csv.reader(codecs.open('test_data.csv','r','utf-8'))
for line in csv_file:
print(line)
测试结果
D:\Anaconda\python.exe E:/projects/python/python_deoms/CSV-demo/CSV_Demo.py
["'name'", "'age'"]
["'tao'", "'12'"]
["'hong'", "'13'"]
["'明'", "'15'"]
根据结果,我们看到,我们成功读出了csv中的内容
关于python中的format字符串格式化
tp1 = "i am {}, age {}, {}".format("seven", 18, 'alex')
tp2 = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
tp3 = "i am {0}, age {1}, really {0}".format("seven", 18)
tp4 = "i am {0}, age {1}, really {0}".format(*["seven", 18])
tp5 = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
tp6 = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
tp7 = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
tp8 = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
tp9 = "i am {:s}, age {:d}".format(*["seven", 18])
tp10 = "i am {name:s}, age {age:d}".format(name="seven", age=18)
tp11 = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})