head first python 第四章

第四章 主题为用持久存储!这里存储的地方是本文件。
这里介绍了本地文件的基本操作方法;以及用打开文件python提供的几种方式,包括一些细节。来一一展开。
先看整体代码。 代码分为两块
第一个try except 语句块是用来读取文件‘sketch.txt’文件的中的数据,分别存放与man与other这两个list里面。
第二个语句块 把man与other分别放入man_data.txt 与other_data.txt 两个文件。

man=[]
other=[]
import os
os.chdir('D:\python\chapter3')
os.getcwd()

try:
    data=open('sketch.txt','r');
    for each_line in data:
        try:
            print(each_line,end='')
            (who,who_talk)=each_line.split(':',1)
            if(who=='Man'):
                man.append(who_talk)
            if(who=='Other Man'):
                other.append(who_talk)
        except ValueError:
            pass

except IOError as err :
    print(str(err))
finally:
    if 'data' in locals():
        data.close()
try:
    man_file=open('man_data1.txt','w')
    other_file=open('other_data1.txt','w')
    print(man,file=man_file)
    print(other,file=other_file)

except IOError as err:
    print(str(err))
finally:
    data_locals =locals()
    print(data_locals)
    if 'man_file' in locals():
        man_file.close()
    if  'other_file' in locals():
        other_file.close()

来说细节
1. 文件的打开方式

data=open('sketch.txt','r');

open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise IOError upon failure.
之所以用stream来说明这里的返回值,是因为在 rb 模式下返回的二进制,在rt(t为默认) 返回的是string。(** text mode (the default, or when
‘t’ is appended to the mode argument), the contents of the file are
returned as strings, t**)
但文件读取的数据能用for get in data 直接来遍历;在一般在str中添加几个’\n’却不行。那么这里背后一定做了某种处理

===============================================================
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)
========= ===============================================================
The default mode is ‘rt’ (open for reading text). For binary random
access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while
‘r+b’ opens the file without truncation. The ‘x’ mode implies ‘w’ and
raises an FileExistsError if the file already exists.

data.readline()返回一行
data.seek(0)文件指针返回初始位置

2.try except finally 语句块

    for each_line in data:
        try:
            print(each_line,end='')
            (who,who_talk)=each_line.split(':',1)
            if(who=='Man'):
                man.append(who_talk)
            if(who=='Other Man'):
                other.append(who_talk)
        except ValueError:
            pass

循环体内的try except ;比if else语句包容性好;做完判断后还能保证for循环的执行,很不错哦!

3.文件的更新
在这里在强调一下,文件修改后只有close才能存储完数据。每个文件都需要关闭~。。
w模式会删除全部数据
w+会在数据后添加
a创建文件,如果存在会抛出异常。
当然存在文件关两次的可能性,那么在这里如何判断呢?

 if 'man_file' in locals():
        man_file.close()

locals返回的是一个字典,包含了本地的所有变量~。
但是不支持遍历,因为每次遍历时都会产生新的遍历而改变locals返回的对应值。
那么如果想遍历有方法吗?
有的

copy
import copy
x = copy.copy(locals())

x = copy.deepcopy(locals())
 浅拷贝与深拷贝。浅拷贝只拷贝了当前指针所指向对象的值;不管是值还是引用。
 深拷贝,将引用与引用的引用的值。。都进行拷贝。

额,集合类型貌似要单开一篇来搞搞。增、删、查、遍历各记录一下~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值