Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

Tôi cần chuyển đổi một loạt các tệp thành UTF-8 trong Python và tôi gặp sự cố với phần "Chuyển đổi tệp".

Tôi muốn làm tương đương:

iconv -t utf-8 $file > converted/$file # this is shell code

Thanks!

Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

Dzinx

53.2K10 Huy hiệu vàng60 Huy hiệu bạc78 Huy hiệu đồng10 gold badges60 silver badges78 bronze badges

Hỏi ngày 10 tháng 10 năm 2008 lúc 13:50Oct 10, 2008 at 13:50

Bạn có thể sử dụng mô -đun Codecs, như thế này:

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

Chỉnh sửa: Đã thêm tham số

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
1 để kiểm soát kích thước chunk tệp.: added
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
1 parameter to control file chunk size.

K Dawg

12.9k9 Huy hiệu vàng33 Huy hiệu bạc65 Huy hiệu Đồng9 gold badges33 silver badges65 bronze badges

Đã trả lời ngày 10 tháng 10 năm 2008 lúc 13:59Oct 10, 2008 at 13:59

2

Điều này làm việc cho tôi trong một bài kiểm tra nhỏ:

sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")

target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))

Đã trả lời ngày 10 tháng 10 năm 2008 lúc 14:07Oct 10, 2008 at 14:07

StaalestaaleStaale

26.6K23 Huy hiệu vàng65 Huy hiệu bạc85 Huy hiệu Đồng23 gold badges65 silver badges85 bronze badges

4

Cảm ơn các câu trả lời, nó hoạt động!

Và vì các tệp nguồn ở các định dạng hỗn hợp, tôi đã thêm một danh sách các định dạng nguồn sẽ được thử theo trình tự (

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
2) và trên
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
3 Tôi thử định dạng tiếp theo:

from __future__ import with_statement

import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector

targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()

def get_encoding_type(current_file):
    detector.reset()
    for line in file(current_file):
        detector.feed(line)
        if detector.done: break
    detector.close()
    return detector.result['encoding']

def convertFileBestGuess(filename):
   sourceFormats = ['ascii', 'iso-8859-1']
   for format in sourceFormats:
     try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
      except UnicodeDecodeError:
        pass

def convertFileWithDetection(fileName):
    print("Converting '" + fileName + "'...")
    format=get_encoding_type(fileName)
    try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
    except UnicodeDecodeError:
        pass

    print("Error: failed to convert '" + fileName + "'.")


def writeConversion(file):
    with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
        for line in file:
            targetFile.write(line)

# Off topic: get the file list and call convertFile on each file
# ...

.

Foon

5.95011 huy hiệu vàng39 Huy hiệu bạc41 Huy hiệu đồng11 gold badges39 silver badges41 bronze badges

Đã trả lời ngày 10 tháng 10 năm 2008 lúc 16:14Oct 10, 2008 at 16:14

3

Trả lời cho loại mã hóa nguồn không xác địnhunknown source encoding type

Dựa trên @Sébastien Roccaserra

python3.6

import os    
from chardet import detect

# get file encoding type
def get_encoding_type(file):
    with open(file, 'rb') as f:
        rawdata = f.read()
    return detect(rawdata)['encoding']

from_codec = get_encoding_type(srcfile)

# add try: except block for reliability
try: 
    with open(srcfile, 'r', encoding=from_codec) as f, open(trgfile, 'w', encoding='utf-8') as e:
        text = f.read() # for small files, for big use chunks
        e.write(text)

    os.remove(srcfile) # remove old encoding file
    os.rename(trgfile, srcfile) # rename new encoding
except UnicodeDecodeError:
    print('Decode Error')
except UnicodeEncodeError:
    print('Encode Error')

Đã trả lời ngày 19 tháng 12 năm 2018 lúc 12:59Dec 19, 2018 at 12:59

Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

Senseisole SenseiSole Sensei

3293 Huy hiệu bạc8 Huy hiệu Đồng3 silver badges8 bronze badges

Bạn có thể sử dụng một lớp lót này (giả sử bạn muốn chuyển đổi từ UTF16 sang UTF8)

    python -c "from pathlib import Path; path = Path('yourfile.txt') ; path.write_text(path.read_text(encoding='utf16'), encoding='utf8')"

Trong đó

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
4 là một đường dẫn đến tệp $ của bạn.

Để làm việc này, bạn cần Python 3.4 hoặc mới hơn (có thể ngày nay bạn làm).

Bên dưới một phiên bản dễ đọc hơn của mã ở trên

from pathlib import Path
path = Path("yourfile.txt")
path.write_text(path.read_text(encoding="utf16"), encoding="utf8")

Đã trả lời ngày 26 tháng 4 năm 2021 lúc 14:43Apr 26, 2021 at 14:43

Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

CesccescCesc

7397 Huy hiệu bạc16 Huy hiệu Đồng7 silver badges16 bronze badges

1

Đây là hàm Python3 để chuyển đổi bất kỳ tệp văn bản nào thành mã có mã hóa UTF-8. (mà không sử dụng các gói không cần thiết)Python3 function for converting any text file into the one with UTF-8 encoding. (without using unnecessary packages)

def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'):
    with open(filename, 'r', encoding=encoding_from) as fr:
        with open(newFilename, 'w', encoding=encoding_to) as fw:
            for line in fr:
                fw.write(line[:-1]+'\r\n')

Bạn có thể sử dụng nó dễ dàng trong một vòng lặp để chuyển đổi danh sách các tệp.

Đã trả lời ngày 8 tháng 1 năm 2017 lúc 17:58Jan 8, 2017 at 17:58

MojiprogmojiprogMojiProg

1.5921 Huy hiệu vàng14 Huy hiệu bạc8 Huy hiệu đồng1 gold badge14 silver badges8 bronze badges

2

Để đoán mã mã hóa là gì, bạn có thể sử dụng lệnh

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
5 *NIX.

Example:

$ file --mime jumper.xml

jumper.xml: application/xml; charset=utf-8

Đã trả lời ngày 8 tháng 2 năm 2012 lúc 19:44Feb 8, 2012 at 19:44

RicardoricardoRicardo

5988 Huy hiệu bạc11 Huy hiệu đồng8 silver badges11 bronze badges

1

Đây là phương pháp vũ lực của tôi. Nó cũng quan tâm đến việc trộn lẫn \ n và \ r \ n trong đầu vào.

    # open the CSV file
    inputfile = open(filelocation, 'rb')
    outputfile = open(outputfilelocation, 'w', encoding='utf-8')
    for line in inputfile:
        if line[-2:] == b'\r\n' or line[-2:] == b'\n\r':
            output = line[:-2].decode('utf-8', 'replace') + '\n'
        elif line[-1:] == b'\r' or line[-1:] == b'\n':
            output = line[:-1].decode('utf-8', 'replace') + '\n'
        else:
            output = line.decode('utf-8', 'replace') + '\n'
        outputfile.write(output)
    outputfile.close()
except BaseException as error:
    cfg.log(self.outf, "Error(18): opening CSV-file " + filelocation + " failed: " + str(error))
    self.loadedwitherrors = 1
    return ([])
try:
    # open the CSV-file of this source table
    csvreader = csv.reader(open(outputfilelocation, "rU"), delimiter=delimitervalue, quoting=quotevalue, dialect=csv.excel_tab)
except BaseException as error:
    cfg.log(self.outf, "Error(19): reading CSV-file " + filelocation + " failed: " + str(error))

Đã trả lời ngày 30 tháng 11 năm 2018 lúc 7:35Nov 30, 2018 at 7:35

Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

Chuyển đổi tất cả các tập tin trong một mã hóa sang UTF-8. Nó là đệ quy và có thể lọc tệp theo hậu tố. Cảm ơn @Sole Sensei

import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
0

Đã trả lời ngày 18 tháng 12 năm 2021 lúc 15:07Dec 18, 2021 at 15:07

Hướng dẫn python convert file to utf-8 - python chuyển đổi tập tin sang utf-8

Jamleejamleejamlee

1.1451 Huy hiệu vàng12 Huy hiệu bạc26 Huy hiệu đồng1 gold badge12 silver badges26 bronze badges

Làm cách nào để chuyển đổi tệp thành UTF

Mã hóa UTF-8 trong Notepad (Windows)..
Mở tệp CSV của bạn trong notepad ..
Nhấp vào Tệp ở góc trên cùng bên trái màn hình của bạn ..
Nhấp vào Lưu dưới dạng ....
Trong hộp thoại xuất hiện, chọn các tùy chọn sau: Trong thả xuống "Lưu dưới dạng loại", chọn tất cả các tệp. Trong thả xuống "mã hóa", chọn UTF-8. ....
Nhấp vào để lưu..

Làm cách nào để mã hóa UTF

UniversalAldetector Nhập UniverseLeTector TargetFormat = 'UTF-8' OutputDir = 'Đã chuyển đổi' DETLE = UniversAltetector () def get_encoding_type (current_file): máy dò. Đặt lại () cho dòng trong tệp (current_file): máy dò. Nguồn cấp dữ liệu (dòng) nếu phát hiện. Xong: Máy dò phá vỡ.

Làm cách nào để thay đổi mã hóa thành UTF

Làm thế nào để chuyển đổi một chuỗi thành UTF-8 trong Python ?..
String1 = "Apple" String2 = "preeti125" String3 = "12345" String4 = "pre@12".
sợi dây.mã hóa (mã hóa = 'UTF-8', lỗi = 'nghiêm ngặt').
# chuỗi unicode chuỗi = 'pythön!'# Mã hóa mặc định thành UTF-8 String_utf = String.Encode () in ('Phiên bản được mã hóa là:', String_utf).

Làm thế nào để bạn mã hóa một tệp văn bản trong Python?

Tập tin & mã hóa ký tự..
Mở một tệp văn bản.Nếu bạn muốn đọc hoặc viết một tệp văn bản có Python, trước tiên phải mở tệp.....
Đọc một tệp văn bản.Một đối tượng tệp không chứa văn bản có thể đọc được.....
Viết một tệp văn bản.....
Thêm mã hóa (UTF-8).....
Mẹo gỡ lỗi.....
Nâng cao hơn: Mở và đọc tất cả các tệp trong một thư mục ..