文件操作,内置函数open()

先看看官方说明:

The default mode is 'r' (open for reading text, synonym of 'rt').  
For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.

As mentioned in the Overview, Python distinguishes between binary and text I/O.  
Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding.
In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

r、w、a 为打开文件的基本模式,分别对应只读、只写、追加模式。
b、t、+ 与以上的文件打开模式组合使用,分别对应二进制模式,文本模式,读写模式。

整理一下:

———————————————————————————————————————————————————————————————————————————————————————
mode    |   描述
———————————————————————————————————————————————————————————————————————————————————————
r       |   以只读方式打开文件(默认),如果文件不存在,则抛出 FileNotFoundError 异常
———————————————————————————————————————————————————————————————————————————————————————
w       |   以只写方式打开文件。指针在开头,文件不存在时创建,文件存在时,则清空再写入新内容。
———————————————————————————————————————————————————————————————————————————————————————
a       |   以追加只写方式打开文件,指针移到文件末尾。文件不存在时创建。
———————————————————————————————————————————————————————————————————————————————————————
x       |   以追加方式打开文件,文件不存在时创建,文件存在时抛出 FileExistsError 异常。
———————————————————————————————————————————————————————————————————————————————————————
r+      |   读写,指针在开头,可以写到文件任何位置
———————————————————————————————————————————————————————————————————————————————————————
w+      |   读写,清空文件内容
———————————————————————————————————————————————————————————————————————————————————————
a+      |   读写,追加,只能写在文件末尾
———————————————————————————————————————————————————————————————————————————————————————

用法

# 打开文件
f = open(file='path', mode='rt')

# 将数据写盘
f.flush()

# 关闭文件
f.close()

在对文件进行操作后,一定要牢记一件事情:file.close()。
如果不关闭,它还驻留在内存中,后面又没有对它的操作,既浪费内存空间,也增加了文件的安全风险。

有另一种方法能够不用手动close()文件,那就是使用 __with__ 的方式打开文件。

with open('users.txt') as f:
    print(f.read())

读文件

f.read(size)         读取文件size个字节内容,返回字符串。如果不指定size,则读取全部内容。
f.readline(size)     读取文件一行size个字节,返回字符串。如果不指定size,则显示一整行。
f.readlines(hint)    读取文件所有行,返回列表。如果hint小于一行的字符数则读取一行,如果hint大于一行小于两行字符数则读取两行,以此类推。
with open('users.txt') as f:
    f.read()
    # 'keith1:18:110\nkeith2:19:111\nkeith3:20:112\nkeith4:21:113'
    
    f.readline()
    # 'keith1:18:110\n'
    
    f.readlines()
    # ['keith1:18:110\n', 'keith2:19:111\n', 'keith3:20:112\n', 'keith4:21:113']

在python中,'\n'表示换行,这也是unix系统中的规范。但是在windows系统中,用'\r\n'表示换行。不过还好,python在处理的时候,会自动将'\r\n'转换为'\n'。

遍历文件

with open(file='users.txt') as f:
    for line in f:
        print(line)

for 循环是一行一行地读取文件内容,每次扫描一行,遇到结束符号\n表示本行结束。

文件指针

指针就是文件操作的位置。

获取指针当前位置

>>> help(f.tell)
Help on built-in function tell:

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

移动指针

>>> help(f.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 默认为起始位置,偏移量为0或者正数。
    * 1 -- current stream position; offset may be negative 当前位置,偏移量可以是负数。
    * 2 -- end of stream; offset is usually negative 结束位置,偏移量通常是负数。

    Return the new absolute position.

whence 表示从何处开始。
cookie 表示相对 whence 的偏移量。

>>> f=open('users.txt')
>>> f.tell()
0
>>> f.read(2)
'ke'
>>> f.tell()
2
>>> f.read(3)
'ith'
>>> f.tell()
5
>>> f.seek(0)
0
>>> f.tell()
0

需要注意的是,seek 移动指针之前默认会先调用 flush 方法。

参考文档

posted @ 2017-10-03 00:55  KeithTt  阅读(585)  评论(0编辑  收藏  举报