Python之把字符串写入文件然后从文件中读出字符串
以下是将字符串写入文件并从文件中读出字符串的Python代码示例:
# 将字符串写入文件
string = 'Hello, world!'
with open('file.txt', 'w') as f:
f.write(string)
# 从文件中读出字符串
with open('file.txt', 'r') as f:
string = f.read()
print(string) # 输出:Hello, world!
在上述示例中,我们使用open()
函数打开一个文本文件(即'w'
和'r'
模式),然后使用write()
和read()
方法将字符串写入文件并从文件中读出字符串。注意,在写入文件时,我们需要将字符串对象作为参数传递给write()
方法,而在读取文件时,read()
方法将返回一个字符串对象。