简体   繁体   English

包含字节的 dat 文件的特定代码(Python)

[英]Specific codes for a dat file that contains bytes (Python)

I have another doubt related to reading the dat file.我还有一个与读取 dat 文件有关的疑问。

The file format is DAT file (.dat)文件格式为 DAT 文件 (.dat)

The content inside the file is in bytes.文件内的内容以字节为单位。

When I tried the run open file code, the program built and ran successfully.当我尝试运行打开文件代码时,程序构建并成功运行。 However, the python shell has no output (I can't see the contents from the file).但是,python shell 没有输出(我看不到文件中的内容)。

Since the content inside the file is in bytes, should I modify the code ?由于文件内的内容以字节为单位,我应该修改代码吗? What is the code to use for bytes?用于字节的代码是什么?

Thank you.谢谢你。

There is no "DAT" file format and, as you say, the file contains bytes - as do all files.没有“DAT”文件格式,正如您所说,该文件包含字节 - 所有文件也是如此。

It's possible that the file contains binary data for which it's best to open the file in binary mode.文件可能包含二进制数据,最好以二进制模式打开文件。 You do that by specifying b as part of the mode parameter to open() , like this:您可以通过将b指定为open()mode参数的一部分来实现,如下所示:

f = open('file.dat', 'rb')
data = f.read()    # read the entire file into data
print(data)
f.close()

Note that the full mode parameter is set to rb which means open the file in binary mode for reading.请注意,完整mode参数设置为rb ,这意味着以二进制模式打开文件进行读取。

A better way is to use with :更好的方法是使用with

with open('file.dat', 'rb') as f:
    data = f.read()
    print(data)

No need to explicitly close the file.无需显式关闭文件。

If you know that the file contains text , possibly encoded in some specific encoding, eg UTF8, then you can specify the encoding when you open the file (Python 3):如果您知道文件包含text ,可能以某种特定编码(例如 UTF8)进行编码,那么您可以在打开文件时指定编码(Python 3):

with open('file.dat', encoding='UTF8') as f:
    for line in f:
        print(line)

In Python 2 you can use io.open() .在 Python 2 中,您可以使用io.open()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM