一.前言 一般来说,为了方便,使用python的时候都会使用csv模块去写数据到csv文件,但是写入中文的时候,经常会报错: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) 我试过直接用utf8编码打开文件,然后直接将要写入的字段拼接为逗号分隔的字符串,虽然能解决中文写入的问题,但是操作很麻烦.而且直接使用excel打开的时候,还是会显示乱码.
直接上代码: # 读文件 def get_venue(file): fname = file # 文件名 # 获取数据长度 len = 0 with open(fname, 'r+', encoding='utf-8') as f: for line in f.readlines(): len += 1 # 创建数组,并赋值 list = [[None] * len for i in range(2)] i = 0 with open(fname, 'r+', encoding='utf-8')
with open("name.txt",'r') as read_file: for name in read_file: list_name = (name.split(',')) quchong = list(set(list_name)) with open("server_name",'w') as write_file: for item in quchong: write_file.writelines(item + '\n')
0.2 2016.09.26 11:28* 字数 216 阅读 8053评论 2喜欢 5 最近一段时间的学习中发现,Python基本和中文字符杠上了.如果能把各种编码问题解决了,基本上也算对Python比较熟悉了. For UTF-8 encoding, Excel requires BOM (byte order mark) codepoint written at the start of the file or it will assume ANSI encoding, which is
背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlwt 其实是没有直接实现: 打开已有的excel文件,然后在文件最后写入,添加新数据 的函数的. 只不过,可以利用: Working with Excel Files in Python 中的库,组合实现. 2. writing to existing workbook using xlwt 给出了示