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


  1. 我有一个 UTF-16-LE 编码的.txt文件。
  2. 我想删除标题(第一行(并将其保存在 ANSI 中
  3. 我可以这样做,但我需要每天为 150 个 txt 文件执行此操作
  4. 所以我想用Python来自动完成它。

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

*"返回mbcs_encode(输入,自我错误([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()

一位高贵的贡献者帮助我解决了这个问题,我现在发布了它,以便每个人都可以从中受益并节省时间。 我们不是尝试写入所有内容,而是列出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)

最新更新