python学习笔记—文件篇

文件

创建文件对象
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)
'''
	 file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
'''
#	即如果文件和程序在同一目录下,filename写文件名即可
#	如果不在同一目录,需要写下文件所在绝对路径
'''
	encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent.
'''
#	encodeing为文件的编码格式,如不声明,默认为系统编码, windows下为gbk

mode:

'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) 已弃用
'r+'	  写读模式,读正常读,写操作要在文件最后写
'w+'	  读写模式 将清空文件,读按光标位置往下读
'a+'	  追加读模式 初始光标在文件末尾,读操作按光标位置,写操作在文件末尾往下写
调用方法进行文件操作

tell() :返回文件光标所在位置,初始默认为0

seek() :重新定义文件光标位置

flush() : 将内存中缓存区数据全写入硬盘(为安全考虑防断电)

trancate():将文件按所输入参数位置截断

readline() : 读取文件的一行

readlines() : 读取文件的每一行,并返回一个列表 注:通常不常用,文件过大时读取文件存进列表 太占内存

推荐读取文件方式:

​for i in file(文本对象):
​ print(i)
for循环内部将文本对象处理成一个迭代器,当用到某行时文本对象调用进内存,不用时不占内存

关闭文件

f.close() # 将缓存区的内存写入硬盘,即文件操作生效

文件句柄

在文件I/O中,要从一个文件读取数据,应用程序首先要调用操作系统函数并传送文件名,并选一个到该文件的路径来打开文件。该函数取回一个顺序号,即文件句柄(file handle),该文件句柄对于打开的文件是唯一的识别依据。

文件修改

因为在文件各种追加模式中,写操作只能在文件末尾执行,所以无法修改文件中的内容,即文件在磁盘存储是固定的,我们只能创建一个新的文件,在写入新的文件时修改。

with语句

with open(‘filename’,’mode’) as f:

​ 文件操作

还可以同时生成两个文件对象(拿到两个文件句柄):

with open(‘filename1’,’mode1’) as obj1,open(‘filename2’,’mode2’) as obj2:

​ 文件操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值