tensorflow.gfile.GFile()的读取和写入模式详解及示例
发布时间:2023-12-29 07:39:44
tensorflow.gfile.GFile()是TensorFlow中的文件操作类,用于读取和写入文件。它支持许多不同的读取和写入模式,如读取二进制文件、读取文本文件、写入二进制文件和写入文本文件等。下面将详细介绍这些读写模式,并提供示例来说明使用方法。
1. 读取模式:
- 'r':以文本模式读取文件(默认模式)。
- 'rb':以二进制模式读取文件。
示例1:以文本模式读取文件
with tensorflow.gfile.GFile('file.txt', mode='r') as f:
contents = f.read()
print(contents)
示例2:以二进制模式读取文件
with tensorflow.gfile.GFile('file.bin', mode='rb') as f:
contents = f.read()
print(contents)
2. 写入模式:
- 'w':以文本模式写入文件,会覆盖原有内容。
- 'a':以文本模式追加写入文件,不会覆盖原有内容。
- 'wb':以二进制模式写入文件,会覆盖原有内容。
- 'ab':以二进制模式追加写入文件,不会覆盖原有内容。
示例3:以文本模式写入文件
contents = "Hello, World!"
with tensorflow.gfile.GFile('output.txt', mode='w') as f:
f.write(contents)
示例4:以文本模式追加写入文件
contents = "Hello, TensorFlow!"
with tensorflow.gfile.GFile('output.txt', mode='a') as f:
f.write(contents)
示例5:以二进制模式写入文件
contents = b'\x01\x02\x03\x04\x05'
with tensorflow.gfile.GFile('output.bin', mode='wb') as f:
f.write(contents)
示例6:以二进制模式追加写入文件
contents = b'\x06\x07\x08\x09\x0A'
with tensorflow.gfile.GFile('output.bin', mode='ab') as f:
f.write(contents)
需要注意的是,使用tensorflow.gfile.GFile()读写文件时,需要使用with语句,这样可以确保在文件操作完毕后自动关闭文件。
