打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python学习笔记《Python核心编程》第9章 文件和输入输出
Python学习笔记《Python核心编程》第9章 文件和输入输出
2013-01-22 22:17 by VVG, 97 阅读, 0 评论,收藏,编辑
9.1 文件内建函数
open() 内建函数成功打开文件后返回一个文件对象,否则引发一个错误。基本语法:
flie_object = open(file_name,access_mode='r',buffering=-1)
file_name 是包含要打开的文件名字的路径,可以试相对路径或者绝对路径。可选变量access_mode是一个字符串,代表文件打开的模式。
文件使用‘r’,‘w’,或者是‘a’模式来代开,代表读取,写入和追加,还有一个‘U’模式,代表通用换行符支持 ,另外一个可选参数buffering用于指示访问文件所采用
的缓冲方式,其中0表示不缓冲,1表示只缓冲一行数据,大于1的值代表使用给定值作为缓冲区大小。
文件对象的访问模式
r     以读方式打开
w    以写方式打开(清空),文件不存在时创建新文件
a    以追加的模式打开,从文件末尾开始,必要时创建新文件
r+  以读写模式打开              w+  以读写模式打开              a+  以读写模式打开
rb  以二进制读模式打开         wb  以二进制写模式打开         ab  以二进制追加模式打开
rb+ 以二进制读写模式打开     wb+ 以二进制读写模式打开     ab+  以二进制读写模式打开
注:工厂函数file() 和 open() 具有相同功能,可以任意替换。
file = open('C:/Users/Administrator/Desktop/Python/testpy.txt','a') file.write('这是追加的内容!!!!!!!!!!!!!!!!!!!!!!!!!') file.close() file = open('C:/Users/Administrator/Desktop/Python/testpy.txt','w') file.write('这是重写的内容,会清除以前的数据!!!!!!!!!!!!!!!!!!!!!!!!!') file.close() file = open('C:/Users/Administrator/Desktop/Python/testpy.txt','r') readlines = file.readlines()
9.2 文件内建方法
读取方法:
read()  方法用来直接读取字节到字符串中, 不带参数表示全部读取,参数表示读取多少个字节
readline()   方法读取打开文件的一行,如果提供参数表示读取字节数,默认参数是-1,代表行的结尾
readlines()  方法会读取所有(剩余的)行然后把他们作为一个字符串列表返回。可选参数代表返回的最大字节大小。
输出方法:
write()  方法表示写入到文件中去
writelines()   方法是针对列表的操作,接受一个字符串列表作为参数,写入文件。行结束符不会自动加入。
核心笔记: 使用输入方法read() 或者 readlines() 从文件中读取行时,python并不会删除行结尾符。
文件内移动:
seek()  方法,移动文件指针到不同的位置。
tell()  显示文件当前指针的位置。
文件迭代:
for eachline in f: #一行一行访问文件,eachline 代表文本文件的一行(包含末尾的行结束符) print eachline,
close()   关闭文件结束对它的访问。
核心笔记:python os模块有5个很有用的属性如下:  不管使用什么平台,只要导入了OS模块,这些变量自动会被设置为正确的值
os模块属性                                  描述
linesep                                用于在文件中分隔行的字符串
sep                                    用来分隔文件路径名的字符串
pathsep                              用于分隔文件路径的字符串
curdir                                 当前工作目录的字符串名称
pardir                                 父目录字符串名称
以下为win7下的值:
import osos.linesep>>> '\r\n'os.sep>>> '\\' os.curdir>>> '.'os.pathsep>>> ';'os.pardir>>> '..'
truncate() 方法,接受一个size作为参数,文件被截断最多size字节处。
写入文件示例:
import osfilename = raw_input('Enter file name:')fobj = open(filename,'w')while True: aLine = raw_input('Enter a line("." to quit):') if aLine != ".": fobj.write('%s%s' % (aLine,os.linesep)) else: breakfobj.close()
seek()  tell()   函数示例:
f = open('D:/PythonLearn/vvgtest','w+')f.tell() # 0f.write('test line l\n') #加入一个长为12的字符串[0-11]f.tell() # 12f.write('test line 2\n') #加入一个长为12的字符串[12-23]f.tell() # 告诉我当前位置 24f.seek(-12,1) #向后移12个字节f.tell() # 12f.readline() # 'test line 2'f.seek(0,0) # 回到最开始f.readline() # 'test line 1'f.close()
文件对象方法
文件对象方法操作
file.close()关闭文件
file.fileno()
返回文件的描述符(file descriptor,FD,整型值)
file.flush()  刷新文件内部缓冲区
file.isatty()判断file是否是一个类tty设备
file.next()返回文件的下一行
file.read(siez=-1)从文件读取size个字节,未给定size或给定负值时,读取剩余的所有字节
file.readline(size=-1)从文件读取并返回一行,或返回最大size个字符
file.readlines(sizhint=0)读取文件的所有航并作为一个列表放回,包含所有的行结束符
file.xreadlines()用于迭代,可以替换readlines()的一个更高效的方法
file.seek(off,whence=0)在文件中移动文件指针,冲whence(0代表文件开始,1代表当前位置,2代表文件末尾)便宜off字节
file.tell()返回当前在文件中的位置
file.write(str)向文件写入字符串
file.writelines(seq)
向文件写入字符串序列seq;seq应该是一个返回字符串的可迭代对象
9.4 文件内建属性
file.name       返回文件名(包含路径)
file.mode       返回文件打开模式
file.closed      返回文件是否已经关闭
file.encoding   返回文件的编码
标准文件:
python中可以通过sys模块访问文件的句柄,导入sys模块后可以使sys.stdin,sysl.stdout,sys.stderr访问。print语句输出到sys.stdout;内建raw_input()通常从sys.stdin接受输入。
文件系统:
os 模块的文件/目录访问函数
函数                                                            描述
-----------------------------文件处理----------------------------------------
mkfifo()/mknod()                                   创建命名管道/创建文件系统节点
remove()/unlink()                                  删除文件
rename()/renames()                              重命名文件
*stat()                                                返回文件信息?
symlink()                                             创建符号链接
utime()                                               更新时间戳
temfile()                                              创建并打开一个新的临时文件
walk()                                                生成一个目录树下的所有文件名
---------------------------------目录/文件夹---------------------------------------
chdir()/fchdir()                                    改变当前工作目录/通过一个文件描述符改变当前工作目录
chroot()                                             改变当前进程的根目录
listdir()                                               列出指定目录文件
getcwd()/getcwdu()                             返回当前工作目录
mkdir()/makedirs()                               创建目录/创建多层目录
rmdir()/removedirs()                            删除目录/删除多层目录
----------------------------------访问权限----------------------------
access()                                              检验权限模式
chmod()                                              改变权限模式
chown()/lchown()                                 改变owner和groupID/功能相同,但不会跟踪连接
umask()                                              设置默认权限模式
------------------------------- 文件描述符操作----------------------------
open()                                                底层操作系统open
read()/write()                                       根据文件描述符读取/写入数据
dup()/dup2()                                       赋值文件描述符号
-------------------------------设备号------------------------------------
makedev()                                          从major和minor设备号创建一个原始设备号
major()/minor()                                   从原始设备号获得 major/minor 设备号
os.path 模块中的路径名访问函数
函数                                                             描述
-----------------------------分隔----------------------------------
basename()                                       去掉目录路径,返回文件名
dirname()                                          去掉文件名,返回目录路径
join()                                                将分离的各部分组合成一个路径
split()                                                返回(dirname(),basename())元组
splitdrive()                                         返回(drivename,pathname)元组
splitext()                                           返回(filename,extension)元组
-------------------------------信息-----------------------------------------
getatime()                                         返回最近访问时间
getctime()                                         返回文件创建时间
getmtime()                                        返回最近文件修改时间
getsize()                                           返回文件大小
-----------------------------查询----------------------------------
exists()                                            指定路径(文件或目录)是否存在
isabs()                                             指定路径是否为绝对路径
isdir()                                               指定路径是否存在且为一个目录
isfile()                                              指定路径是否存在且为一个文件
islink()                                             指定路径是否存在且为以个符号链接
ismount()                                        指定路径是否存在且为以个挂载点
samefile()                                        两个路径名是否指向同一个文件
------------------------------------------------------------------------------------------END
os 和 os.path模块示例:
#!/usr/bin/env pythonimport osfor tmpdir in('/tmp','D:/PythonLearn/temp'): if os.path.isdir(tmpdir): # os.path.isdir 指定路径是否存在且为一个目录 break else: print 'no temp directory availiable' tmpdir = '' if tmpdir: os.chdir(tmpdir) #os.chdir() 改变当前工作目录 cwd = os.getcwd() #os.getcwd() 返回当前工作目录 print '*** current temporary directory' print cwd print '*** creating example directory...' os.mkdir('example') #os.mkdir() 创建目录 os.chdir('example') #os.chdir() 改变当前工作目录 cwd = os.getcwd() print '*** new working directory: ' print cwd print '*** original directory listing: ' print os.listdir(cwd) #os.listdir 列出指定目录文件 print '*** creating test file...' fobj = open('test','w') fobj.write('foo\n') fobj.write('bar\n') fobj.close() print '*** updated directory listing: ' print os.listdir(cwd) #os.listdir() 列出指定目录文件 print "*** renameing 'test' to 'filetest.txt'" os.rename('test','filetest.txt') #os.rename 重命名文件 print '*** updated directory listing: ' print os.listdir(cwd) path = os.path.join(cwd,os.listdir(cwd)[0]) # os.path.join() 将分离的各部分组合成一个路径 print '*** full file pathname' print path print '***(pathname,basename==)' print os.path.split(path) # os.path.split() 返回(dirname(),basename())元组 print '***(filename,extenion)==' print os.path.splitext(os.path.basename(path)) # os.path.splitext() 返回(filename,extension)元组 os.path.basename()去掉目录返回文件名 print '*** diaplaying file contents:' fobj = open(path) for eachLine in fobj: print eachLine, fobj.close() print '*** deleting test file' os.remove(path) #删除文件 print '*** updated directory listing:' print os.listdir(cwd) os.chdir(os.pardir) print '*** deleting test drectory' os.rmdir('example') print '***DONE'
输出:
>>> ================================ RESTART ================================>>> no temp directory availiable*** current temporary directoryD:\PythonLearn\temp*** creating example directory...*** new working directory: D:\PythonLearn\temp\example*** original directory listing: []*** creating test file...*** updated directory listing: ['test']*** renameing 'test' to 'filetest.txt'*** updated directory listing: ['filetest.txt']*** full file pathnameD:\PythonLearn\temp\example\filetest.txt***(pathname,basename==)('D:\\PythonLearn\\temp\\example', 'filetest.txt')***(filename,extenion)==('filetest', '.txt')*** diaplaying file contents:foobar*** deleting test file*** updated directory listing:[]*** deleting test drectory***DONE>>>
9.5 永久存储模块
pickle 和 marshal 模块:可以用来转换并储存python对象。该过程将基本类型复杂的对象转换为一个二进制数据集合,这样就可以吧数据集合保存起来或通过网络发送
,然后再重新把数据集合恢复原来的对象格式。这个过程被称为数据的扁平化、数据的序列化或者数据的顺序化。
shelve 模块:允许对数据库文件进行并发的读访问,但不允许共享读、写访问。
本章完。
转载请注明出处:http://www.cnblogs.com/NNUF/
分类:Python,原创
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Dave Python练习八--文件和输入输出
Python 错误 IsADirectoryError: [Errno 21] Is a directory 解决方法
python笔记15
python开发之文件操作用法实例
python处理txt文件的常用操作
中秋不吃月饼,复习一些常用函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服