码迷,mamicode.com
首页 > 其他好文 > 详细

IO编程-----读写文件

时间:2017-12-12 21:54:08      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:取数   ref   读写   进制   操作系统   exclusive   cts   wan   gpo   

读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。

读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。

 

open(filemode=‘r‘buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

mode是一个可选字符串,用于指定打开文件的模式。它默认‘r‘打开文本模式下的阅读方式。其他常见的值是‘w‘写(截断文件,如果它已经存在),‘x‘独占创建和‘a‘附加(在一些 Unix系统上,这意味着所有的写入追加到文件的末尾,无论当前的寻找位置)。在文本模式下,如果 编码未指定使用的编码是与平台相关的: locale.getpreferredencoding(False)被称为获取当前的本地编码。(用于读取和写入原始字节使用二进制模式,并保留 编码未指定。)可用的模式是:

CharacterMeaning
‘r‘ open for reading (default)  打开文件阅读
‘w‘ open for writing, truncating the file first  打开并写入文件
‘x‘ open for exclusive creation, failing if the file already exists 创建文件,如果
‘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 newlines mode (deprecated)

 

#读取文件
f=open(/home/wangxy/PycharmProjects/hello.txt, r) #open(文件路径,r表示读)
print(f.read())#成功open后,读取内容
f.close()  #文件使用完毕必须关闭,因为文件对象会占用系统资源

#由于文件读写时都有可能产生IOError,一旦出错,后面的f.close()就不会调用。所以,为了保证无论是否出错都能正确地关闭文件,我们可以使用with语句
#with语句会自动调用close
with open(/home/wangxy/PycharmProjects/hello.txt, r) as f:
    print(f.read())

with open(/home/wangxy/文档/test.py,r) as f:
    #调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。
    #print(f.read(512))
    #是否可读
    print(readable is: %s%f.readable())
    #readline(x) 读一行,x表示读几个字节的内容
    print(f.readline())
    print(f.readline())
    #readlines() 一次性读取所有内容并按行返回list
    print(f.readlines())

#读取二进制文件,比如图片视频,需要标识符为rb
with open(/home/wangxy/图片/1.png,rb) as f:
    print(f.read())

#遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:
with open(/home/wangxy/文档/Command方法分析.py,r,encoding=gbk,errors=ignore) as f:
    print(f.read())


#练习:请将本地一个文本文件读为一个str并打印出来:
fpath=r/home/wangxy/文档/test.py

with open(fpath,r) as f:
    print(f.read())

 

#写入文件

with open(/home/wangxy/PycharmProjects/hello.txt,a) as f:
    f.write(This is write line2!\n)

#创建文件
with open(/home/wangxy/PycharmProjects/testwangxy.txt,x) as f:
    f.write(test create a file!)

 

IO编程-----读写文件

标签:取数   ref   读写   进制   操作系统   exclusive   cts   wan   gpo   

原文地址:http://www.cnblogs.com/wangxy92/p/8028929.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!