thinkpython 第14章 files

---恢复内容开始---

14.1persistence

14.2reading and wroiting

使用open('','w')写入模式打开已经存在的文件时,会清空原先的数据并重新开始,所以需要小心。如果文件不存在,那么将会创建一个新的文件

14.3format operator

write的参数必须是字符串,我们可以使用str()来强制转换,也可以使用格式运算符%。

%d 格式化整数

格式化序列可以出现在字符串的任何位置

如果字符串中有多于一个格式序列,第二个参数必须为一个元组。每个格式序列按次序和元组中的元素对应

14.4filenames and paths

>>> import os
>>> cwd = os.getcwd()
>>> cwd
'C:\Users\吴金阔\Desktop'
>>> import os #os:operating system
>>> cwd = os.getcwd()#cwd:current working directory
>>> os.path.abspath('words.txt')
'C:\Users\吴金阔\Desktop\words.txt'
>>> os.path.abspath('words.txt')#os.path.abspath得到的是一个文件的绝对路径
'C:\Users\吴金阔\Desktop\words.txt'
>>> os.path.exists('words.txt')#检查一个文件或者目录是否存在
True
>>> #如果存在,os.path.isdir检查它是否是一个目录
>>> os.path.isdir('words.txt')
False
>>> os.path.isdir('例会')
True
>>> #类似,os.listdir返回给定目录下的文件(以及其它目录)
>>> os.listdir('例会')
['20170927', '20171011', '20171109', '20171115', '20171129']
>>> def walk(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir,name)#读取一个目录名和一个文件名,并将两者合并为一个完整路径
        if os.path.isfile(path):
            print(path)
        else:
            walk(path)
import os

def walk(dirname):
    for name in os.listdir(dirname):
        path = os.path.join(dirname, name)
        if os.path.isfile(path):
            print(path)
        else:
            walk(path)

def walk2(dirname):
    for root, dirs, files in os.walk(dirname):
        for filename in files:
            print(os.path.join(root, filename))

if __name__ == '__main__':
    walk('.')
    walk2('.')

14.5catching exceptions

我们可以使用try语句处理异常(捕获异常)

try:
    fin = open('bad_file')
    for line in fin:
        priunt(line)
    fin.close()
except:
    print('sth went wrong')

14.6databases

没有anydbm模块。。

14.7pickling

pickle模块能将任何类型的对象翻译成适合在数据库中储存的字符串,同时能将字符串还原成对象。

pickle.dumps读取一个对象作为参数,并返回一个表征字符串.

>>> import pickle
>>> t1 = [1,2,3]
>>> t2 = pickle.dumps(t1)
>>> t2
b'x80x03]qx00(Kx01Kx02Kx03e.'
>>> t3 = pickle.loads(t2)#载入字符串
>>> t3
[1, 2, 3]
>>> t1 == t3
True
>>> t1 is t3
False

14.8pipes

14.9writing modules

编写一个wjk.py文件

def linecount(filename):
    count = 0
    for line in open(filename):
        count += 1
    return count
print (linecount('wjk.py'))

运行这个程序,它将读取自身,并打印行数,结果是6

>>> import wjk
6
>>> print (wjk)
<module 'wjk' from 'C:\Users\吴金阔\Desktop\wjk.py'>
>>> wjk.linecount('wjk.py')
6

作为模块的程序通常写成以下结构

>>> if __name__ == '__main__':
    print (linecount('wjk.py'))

    
6

注意:当再次导入一个已经导入的模块,python不会重新读取文件,即使文件发生了改变。如果需要重载一个模块,可以使用内建函数reload(但它本身并不可靠),所以我们最好是重启解释器然后重新导入。

14.10debugging

内建函数repr读取一个对象作为参数,并返回一个表示这个对象的字符串。对于字符串,他将空白符号用反斜杠序号表示

>>> s = '1 2	 3
 4'
>>> print(s)
1 2     3
 4
>>> print (repr(s))
'1 2	 3
 4'
原文地址:https://www.cnblogs.com/Kingwjk/p/7944350.html