如何将 UTF-16-LE txt 文件转换为 ANSI txt 文件并删除 PYTHON 中的 header?

How can i convert a UTF-16-LE txt file to an ANSI txt file and remove the header in PYTHON?

  1. 我有一个 UTF-16-LE 编码的 .txt 文件。
  2. 我想删除 headers(第一行)并将其保存为 ANSI
  3. 我可以手动完成,但我每天需要对 150 个 txt 文件执行此操作
  4. 所以我想使用 Python 自动完成。

但我卡住了, 我试过这段代码,但它不起作用,产生错误:

*return mbcs_encode(输入, self.errors)[0]

UnicodeEncodeError: 'mbcs' 编解码器无法对位置 0--1 中的字符进行编码:无效字符 "*

filename = "filetochangecodec.txt"
path = "C:/Users/fallen/Desktop/New folder/"
pathfile = path + filename
coding1 = "utf-16-le"
coding2 = "ANSI"

f= open(pathfile, 'r', encoding=coding1)
content= f.read()
f.close()
f= open(pathfile, 'w', encoding=coding2)
f.write(content)
f.close()

一位高尚的贡献者帮助我解决了这个问题,我现在post它这样每个人都可以受益并节省时间。 我们没有尝试写入所有内容,而是将 txt 文件的每一行都列成一个列表,然后使用“for”将它们逐一写入新文件。

import os

inpath = r"C:/Users/user/Desktop/insert/"
expath = r"C:/Users/user/Desktop/export/"
encoding1 = "utf-16"
encoding2 = "ansi"


 
input_filename = "text.txt"
input_pathfile = os.path.join(inpath, input_filename)

output_filename = "new_text.txt"
output_pathfile = os.path.join(expath, output_filename)



with open(input_pathfile, 'r', encoding=encoding1) as file_in:
    lines = []
    for line in file_in:
        lines.append(line)

with open(output_pathfile, 'w', encoding='ANSI') as f:
    for line in lines:
        f.write(line)