python读取ini文件utf-16 le,Python-使用BOM解码UTF-16文件

I have a UTF-16 LE file with BOM. I'd like to flip this file in to UTF-8 without BOM so I can parse it using Python.The usual code that I use didn't do the trick, it returned unknown characters instea...
摘要由CSDN通过智能技术生成

I have a UTF-16 LE file with BOM. I'd like to flip this file in to UTF-8 without BOM so I can parse it using Python.

The usual code that I use didn't do the trick, it returned unknown characters instead of the actual file contents.

f = open('dbo.chrRaces.Table.sql').read()

f = str(f).decode('utf-16le', errors='ignore').encode('utf8')

print f

What would be the proper way to decode this file so I can parse through it with f.readlines()?

解决方案

Firstly, you should read in binary mode, otherwise things will get confusing.

Then, check for and remove the BOM, since it is part of the file, but not part of the actual text.

import codecs

encoded_text = open('dbo.chrRaces.Table.sql', 'rb').read() #you should read in binary mode to get the BOM correctly

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 python 的 built-in `open()` 函数来读取 UTF-16LE 格式的文件, 并在其中指定编码为 `'utf-16le'`. 例如: ``` with open('filename.txt', 'r', encoding='utf-16le') as f: data = f.read() ``` 在这里,`'filename.txt'` 是要读取文件的名称,`'r'` 表示以只读模式打开文件,`encoding='utf-16le'`表示文件编码为 UTF-16LE. 读取文件后,变量`data` 就包含了文件中的所有文本. ### 回答2: 要使用Python读取UTF-16 LE格式的文件,可以按照以下步骤进行操作: 1. 打开文件使用内置的`open()`函数打开文件,并指定文件路径和文件访问模式。例如,要打开一个名为`file.txt`的UTF-16 LE格式的文件,可以使用以下代码: ```python file = open('file.txt', 'r', encoding='utf-16-le') ``` 2. 读取文件内容:使用`read()`或`readlines()`方法读取文件内容。例如,可以使用以下代码读取文件的所有内容并打印出来: ```python content = file.read() print(content) ``` 3. 关闭文件使用`close()`方法关闭文件,释放资源。例如: ```python file.close() ``` 完整的示例代码: ```python file = open('file.txt', 'r', encoding='utf-16-le') content = file.read() print(content) file.close() ``` 需要注意的是,打开文件时要指定正确的编码方式,即`utf-16-le`用于UTF-16 LE格式的文件读取文件内容后可以根据需要进行后续操作,比如处理数据、提取信息等。 ### 回答3: 要使用Python读取UTF-16 LE格式的文件,可以按照以下步骤进行操作: 1. 使用`open()`函数打开文件,设置`encoding`参数为`'utf-16-le'`来指定文件的编码格式。例如,`file = open('filename.txt', encoding='utf-16-le')`。 2. 使用`read()`函数读取文件的内容。例如,`content = file.read()`。 3. 可以对读取到的内容进行处理或打印输出。例如,`print(content)`。 4. 最后,记得关闭文件,以释放资源。使用`close()`函数关闭文件。例如,`file.close()`。 以下是一个完整的示例代码: ```python file = open('filename.txt', encoding='utf-16-le') content = file.read() print(content) file.close() ``` 请注意,`filename.txt`应该是真实存在,并且使用UTF-16 LE编码的文件。同时,确保文件的路径正确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值