Reputation: 319
I have two files in UTF-8, I need merge this files with a Python script, for each line in f1 (read by readlines() method), I do a writeline(l) in f2, but I need that f2 be UTF-8 file, How I can dou?
Thanks
Upvotes: 0
Views: 146
Reputation: 395
You can use the open method from the codecs module (instead of open(file,'w')
):
import codecs
fileNames = ['file1.txt', 'file2.txt']
with codecs.open('file3.txt', 'w', 'utf-8') as outfile:
for fname in fileNames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
http://docs.python.org/2/library/codecs.html#codecs.open
Upvotes: 1
Reputation: 2194
How about:
line.encode('utf-8')
in case it's not already encoded with utf-8. It should be though, when both files are initially utf-8. You can also open the file in python with a given encoding:
file = open("C:\test.txt","r", encoding="utf-8")
Upvotes: 0