Python 文件

来源:互联网 发布:php 反射类 编辑:程序博客网 时间:2024/05/01 19:21

Python 文件

首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。

1、打开文件

>>> input = open('data', "r")
字符串"r"代表读取文件。
字符串"w"代表写入文件
字符串"a"代表写入文件末尾。
字符串"b"代表文件是二进制文件

2、读写操作

(1) 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()                     # 关闭文件
(2) read()方法
>>> input = open(filePath, "r") >>> input.read()                       # 读取所有内容,返回一个字符串'Hello World!\nWelcome to Python\nNice to meet you'
(3) readlines()方法
>>> input = open(filePath, "r")>>> input.readlines()                  # 读取所有内容,返回字符串列表['Hello World!\n', 'Welcome to Python\n', 'Nice to meet you']
(4) readline()方法
>>> input = open(filePath, "r")>>> input.readline()                   # 读取一行字符串'Hello World!\n'>>> input.readline()'Welcome to Python\n'>>> input.readline()'Nice to meet you'>>> input.readline()                   # 文件末尾返回空字符串''
(5) for函数
>>> for line in open(filePath, "r"):   # 文件迭代    print line.rstrip(),Hello World! Welcome to Python Nice to meet you

3、pickle模块

(1) 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()
(2) pickle模块读取存储Python对象。
>>> input = open(filePath, "rb")>>> import pickle>>> pickle.load(input)                 # load方法读取列表对象['Hello', 'World']>>> pickle.load(input)                 # load方法读取字典对象{'age': 18, 'name': 'Jack'}

4、shelve模块

(1) shelve模块存储Python对象
>>> L = ["Hello", "World"]>>> D = {"name":"Jack", "age":18}>>> import shelve>>> db = shelve.open("datadb")>>> db["list"] = L>>> db["dict"] = D>>> db.close()
(2) shelve模块读取存储Python对象。
>>> db = shelve.open("datadb")>>> for key in db:print key, "=", db[key]dict = {'age': 18, 'name': 'Jack'}list = ['Hello', 'World']

0 0
原创粉丝点击