poem = """\
Programming is fun
when the work is done
if you wanna make your work also fun:
use Python!
"""
# 打开文件以编辑('w'riting)
f = open('poem.txt', 'w')
f.write(poem)
f.close()
# 如果没有特别指定,
# 将假定启用默认的阅读('r'ead)模式
f = open('poem.txt')
while True:
line = f.readline()
# 零长度指示 EOF
if len(line) == 0:
break
# 每行line的末尾
# 都已经有了换行符
# 因为它是从一个文件中进行读取的
print(line, end='')
# 关闭文件
f.close()
输出:
Programming is fun
when the work is done
if you wanna make your work also fun:
use Python!
打开模式:阅读模式('r')、写入模式('w')、追加模式('a')
还可以选择是通过文本模式('t')还是二进制模式('b')来读取、写入或追加文本。
===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
===============================================================
Pickle
标准模块,通过它你可以将任何春Python对象存储到一个文件中,并在稍后将其取回。这叫做持久地存储对象。
import pickle
shoplistfile = 'shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f)
f.close()
del shoplist
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f)
print(storedlist)
输出:['apple', 'mango', 'carrot']
dump函数——封装(Pickling)
load函数——拆封(UNpickling)
Unicode
# encoding=utf-8
import io
f = io.open("abc.txt", "wt", encoding="utf-8")
f.write(u"Imagine non-English language here")
f.close()
text = io.open("abc.txt", encoding="utf-8").read()
print(text)