在Python中,如何使用文件来写入字节并以tex的形式读取

2024-09-30 20:36:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将字节保存到一个文件中,然后将该文件作为文本读取。我能用一个with吗?我应该用什么,wbrwbr?你知道吗

myBytesVar = b'line1\nline2'
with open('myFile.txt', 'wb') as fw:
    fw.write(myBytesVar)

with open('myFile.txt', 'r') as fr:
    myVar = fr.read()
    print(myVar)

Tags: 文件文本txt字节aswithopenfr
3条回答

如果文件的内容已存储在myBytesVar中,则无需重新读取该文件:

myBytesVar = b'line1\nline2'

with open('myFile.txt', 'wb') as fw:
    fw.write(myBytesVar)

myVar = myBytesVar.decode('utf-8')

Python的编码假设在没有显式编码的情况下以文本形式读取文件是platform-dependent,所以我假设UTF-8可以工作。你知道吗

如果你想用一个“with”:当你写它的时候“wb”是好的。 当你读文件的时候,试试看

myvar = open('MyVar.txt', 'r').read()
print(myvar)

以下是我们应该使用的模式的一些信息:

The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

在这里阅读更多。 https://docs.python.org/3/library/functions.html#open

相关问题 更多 >