首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
1. 打开文件
open()
方法打开文件。
>>> input = open('data', "r")
字符串"r"
代表读取文件。
字符串"w"
代表写入文件。
字符串"a"
代表写入文件末尾。
字符串"b"
代表文件是二进制文件
2. 读写操作
write()
方法
>>> filePath = "myfile.txt"
>>> output = open(filePath, "w") # 打开文件
>>> output.write("Hello World!\n") # 输入内容
>>> output.write("Welcome to Python\n")
>>> output.write("Nice to meet you")
>>> output.close() # 关闭文件
read()
方法
>>> input = open(filePath, "r")
>>> input.read() # 读取所有内容,返回一个字符串
'Hello World!\nWelcome to Python\nNice to meet you'
readlines()
方法
>>> input = open(filePath, "r")
>>> input.readlines() # 读取所有内容,返回字符串列表
['Hello World!\n', 'Welcome to Python\n', 'Nice to meet you']
readline()
方法
>>> input = open(filePath, "r")
>>> input.readline() # 读取一行字符串
'Hello World!\n'
>>> input.readline()
'Welcome to Python\n'
>>> input.readline()
'Nice to meet you'
>>> input.readline() # 文件末尾返回空字符串
''
for
函数
>>> for line in open(filePath, "r"): # 文件迭代
print line.rstrip(),
Hello World! Welcome to Python Nice to meet you
3. pickle模块
pickle
模块用来存储Python对象。
>>> L = ["Hello", "World"]
>>> D = {"name":"Jack", "age":18}
>>> filePath = "mydata.pkl"
>>> output = open(filePath, "wb") # 文件类型是二进制
>>> import pickle
>>> pickle.dump(L, output) # dump方法输入列表对象
>>> pickle.dump(D, output) # dump方法输入字典对象
>>> output.close()
pickle
模块读取存储Python对象。
>>> input = open(filePath, "rb")
>>> import pickle
>>> pickle.load(input) # load方法读取列表对象
['Hello', 'World']
>>> pickle.load(input) # load方法读取字典对象
{'age': 18, 'name': 'Jack'}
4. shelve模块
shelve
模块存储Python对象
>>> L = ["Hello", "World"]
>>> D = {"name":"Jack", "age":18}
>>> import shelve
>>> db = shelve.open("datadb")
>>> db["list"] = L
>>> db["dict"] = D
>>> db.close()
shelve
模块读取存储Python对象。
>>> db = shelve.open("datadb")
>>> for key in db:
print key, "=", db[key]
dict = {'age': 18, 'name': 'Jack'}
list = ['Hello', 'World']
相关文章
Python 数字类型(一)
Python 布尔型(二)
Python 字符串(三)
Python 列表(四)
Python 字典(五)
Python 元组(六)
Python 集合(七)
Python 变量和作用域(八)
Python 语句(九)
Python 函数(十)
Python 类(十一)
Python 模块(十二)
Python 文档(十三)
Python 文件(十四)
Python 异常(十五)
Python 运算符重载(十六)