自学Python之路-Python基础+模块+面向对象

自学Python之路-Python网络编程

自学Python之路-Python并发编程+数据库+前端

自学Python之路-django

自学Python4.1-文件操作

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件(非必须)

一、打开文件

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

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容;】

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

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

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

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

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

模式

描述

r

以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。

rb

以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。

r+

打开一个文件用于读写。文件指针将会放在文件的开头。

rb+

以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。

w

打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

wb

以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

w+

打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

wb+

以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a

打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

ab

以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

a+

打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。

ab+

以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

x

如果文件存在则报错,如果不存在,则创建文件并写内容

二、操作文件

自学Python4.1-文件操作_打开文件

自学Python4.1-文件操作_文件指针_02

class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer.

encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False).

errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict".

newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows:

* On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated.

* On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string.

If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass

def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass

def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass

def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass

def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass

def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass

def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass

def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass

def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass

def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass

def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass

def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass

def write(self, *args, **kwargs): # real signature unknown
写内容
pass

def __getstate__(self, *args, **kwargs): # real signature unknown
pass

def __init__(self, *args, **kwargs): # real signature unknown
pass

@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass

def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass

def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass

buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

_CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

_finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

源码

 1. write(self, *args, **kwargs)  写数据

     read(self, *args, **kwargs)   读取指定字符数据

f=open('test.log','w')
f.write('afaefafafafaf') # 先写入文件
f.close()
f=open('test.log','r')
ret=f.read(6) # 读取6个字符
f.close()
print(ret)

输出 afafae
2. readline(self, *args, **kwargs)  仅读取一行

3. tell(self, *args, **kwargs) 获取指针位置(按字节)
4. seek(self, *args, **kwargs)  指定文件中指针位置
5. truncate(self, *args, **kwargs)  截断数据,仅保留指定之前数据,更新原文件 

三、 关闭文件

这步操作并不是必须的,如果使用open()函数打开文件,那么要记得最终close()文件

如果使用with 语句打开的文件,则不需要。在with 语句主体语句执行完之后,会自动调用close()来关闭文件句柄。语法如下:

with open('db1', 'r', encoding="utf-8") as f1:
for line in f1:
print(line)

同时打开两个文件,如下:

with open('file1', 'r', encoding="utf-8") as f1, open("file2", 'w',encoding="utf-8") as f2:
pass