我正在使用python代碼從許多csv文件中讀取並將編碼設置爲utf8.I閱讀文件時遇到問題我可以讀取所有行,但是當我寫它,它只能寫1行。請幫我檢查我的代碼如下:閱讀許多csv文件,並將其編碼爲utf8使用python
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")
' ''。加入(f.readlines())'應該寫成'f.read()' – jfs
看來OP使用Python 3,否則'encoding'參數不可用於內置open函數。因此'data.decode()'將失敗,因爲'data'已經是Unicode。 – jfs
thx爲您的指南〜 – wcp