Hướng dẫn how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

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 how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

Dzinx

53.3K10 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 how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

Senseisole SenseiSole Sensei

3393 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 how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

CesccescCesc

7697 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.6321 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 how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

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 how to encode a file in python - làm thế nào để mã hóa một tập tin trong python

Jamleejamleejamlee

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

Mã hóa = 'latin1 trong python là gì?

Mã hóa văn bản đơn giản nhất (được gọi là 'Latin-1' hoặc 'ISO-8859-1') ánh xạ các điểm mã 0 NottT được mã hóa với codec này.maps the code points 0–255 to the bytes 0x0 – 0xff , which means that a string object that contains code points above U+00FF can't be encoded with this codec.

Mã hóa trong xử lý tệp Python là gì?

Thông tin mã hóa sau đó được trình phân tích cú pháp Python sử dụng để giải thích tệp bằng cách sử dụng mã hóa đã cho.Đáng chú ý nhất là điều này giúp tăng cường cách giải thích các chữ unicode trong mã nguồn và có thể viết các chữ Unicode bằng cách sử dụng ví dụ:UTF-8 trực tiếp trong một trình soạn thảo unicode Aware.used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.