python读取csv文件编码_读取许多csv文件并将其写入使用python编码的utf8

I'm using python code to read from many csv files and set encoding to utf8.I meet the problem when I read the file I can read all lines but when I write it, it can write only 1 line. Please help me to check my code as below:

def convert_files(files, ascii, to="utf-8"):

for name in files:

#print ("Convert {0} from {1} to {2}").format(name, ascii, to)

with open(name) as f:

print(name)

count = 0

lineno = 0

#this point I want to write the below text into my each new file at the first line

#file_source.write('id;nom;prenom;nom_pere;nom_mere;prenom_pere;prenom_mere;civilite (1=homme 2=f);date_naissance;arrondissement;adresse;ville;code_postal;pays;telephone;email;civilite_demandeur (1=homme 2=f);nom_demandeur;prenom_demandeur;qualite_demandeur;type_acte;nombre_actes\n')

for line in f.readlines():

lineno +=1

if lineno == 1 :

continue

file_source = open(name, mode='w', encoding='utf-8', errors='ignore')

#pass

#print (line)

# start write data to to new file with encode

file_source.write(line)

#file_source.close

#print unicode(line, "cp866").encode("utf-8")

csv_files = find_csv_filenames('./csv', ".csv")

convert_files(csv_files, "cp866")

解决方案

You're reopening the file during every iteration.

for line in f.readlines():

lineno +=1

if lineno == 1 :

continue

#move the following line outside of the for block

file_source = open(name, mode='w', encoding='utf-8', errors='ignore')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值