【问题标题】:In Python, how to use a file for writing bytes in it and reading as text在 Python 中,如何使用文件在其中写入字节并作为文本读取
【发布时间】:2018-04-12 06:54:39
【问题描述】:

我想将字节保存到文件中,然后将该文件作为文本读取。我可以用一个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)

【问题讨论】:

  • 为什么不能直接将myBytesVar 写入文件并与myVar = myBytesVar.decode('utf-8') 一起使用?
  • 谢谢。如果我在脚本开头有coding:utf-8,是否需要utf8?
  • “有一个with”是指这样的事情是可以接受的:with open("myFile.txt", "wb") as outFile, open("myFile.txt", "r") as inFile:?这应该可行,尽管它只是双 with 的语法糖。
  • @HrvojeT:您的 Python 脚本文件本身使用的编码和您的 myFile.txt 使用的编码是两个完全不同的东西。

标签: python filehandler


【解决方案1】:

如果您已经将文件内容存储在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 可以工作。

【讨论】:

    【解决方案2】:

    这里有一些关于我们应该使用什么模式的信息:

    默认模式是'r'(打开阅读文本,'rt'的同义词)。为了 二进制读写访问,模式'w+b'打开并截断文件 为 0 字节。 'r+b' 打开文件而不截断。

    在此处阅读更多信息。 https://docs.python.org/3/library/functions.html#open

    【讨论】:

      【解决方案3】:

      如果你想用一个“with”来做:当你写它时,“wb”很好。 当您阅读文件时尝试一下

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

      【讨论】:

      • 我必须关闭文件吗?
      • 不,它需要什么。当您看到包含 line1line2 的文件“Myfile.txt”时,您已经写入文件“Myfile.txt”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-03
      • 1970-01-01
      相关资源
      最近更新 更多