【每天1分钟】PYTHON基础之文件对象(文件操作)

【每天1分钟】PYTHON基础之文件对象(文件操作)

1.读取文件

1.一般语法

f=open(r'c:\a.txt','r',encoding=’utf-8)
f.read()       # 从头到尾全部打印
f.readlines()  # 按行读,输出成列表
f.readline()   # 从光标开始读一行
f.close()      # 文件操作完成一定要关闭

2.使用with 读取整个文件

.read()

with open(r'c:\a.txt','r',encoding=’utf-8) as file_object:
    contents = file_object.read()

2.使用with 逐行读取
for

with open(r'c:\a.txt','r',encoding=’utf-8) as file_object:
    for line in file_object:

3.包含"文件各行内容"的列表

.readlines()

with open(r'c:\a.txt','r',encoding=’utf-8) as file_object:
    lines = file_object.readlines()

2.写入文件

.write()

with open(r'c:\a.txt','w',encoding=’utf-8) as file_object:
    file_object.write('. . .')
    file_object.writelines(['. . . \n', '. . . \n', '. . . \n'])  # 添加 \n 换行

3.文件打开模式

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  • w,只写模式【不可读;不存在则创建;存在则清空内容】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读; 不存在则创建;存在则只追加内容】

“+” 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

"b"表示以字节的方式操作

  • rb 或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码


4.内建方法

>>> f = open('test','a')
>>> dir(f)
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines']
>>> help(f.seek)          # seek是移动文件指针
Help on built-in function seek:

seek(cookie, whence=0, /) method of _io.TextIOWrapper instance
    Change stream position.
    
    Change the stream position to the given byte offset. The offset is
    interpreted relative to the position indicated by whence.  Values
    for whence are:
    
    * 0 -- start of stream (the default); offset should be zero or positive # 从文件开头算起
    * 1 -- current stream position; offset may be negative                  # 从当前位置算起
    * 2 -- end of stream; offset is usually negative                        # 从文件末尾算起
    
    Return the new absolute position.

>>> help(f.tell)                 # 返回当前文件指针位置
Help on built-in function tell:

tell() method of _io.TextIOWrapper instance
    Return current stream position.

>>> help(f.close)               # 关闭文件
Help on built-in function close:

close() method of _io.TextIOWrapper instance
    Flush and close the IO object.
    
    This method has no effect if the file is already closed.

>>> help(f.flush)             # 把内部缓存区数据立刻写入文件
Help on built-in function flush:

flush() method of _io.TextIOWrapper instance
    Flush write buffers, if applicable.
    
    This is not implemented for read-only and non-blocking streams.

>>> help(f.truncate)         #用于截断文件并返回截断的字节长度。指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除。
Help on built-in function truncate:

truncate(pos=None, /) method of _io.TextIOWrapper instance
    Truncate file to size bytes.
    
    File pointer is left unchanged.  Size defaults to the current IO
    position as reported by tell().  Returns the new size.

>>> 

5.分隔符

python分隔符

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值