Python3基础知识10

1 File 的使用

1.1 读和写文件

open() 将会返回一个 file 对象,基本语法格式如下:

1
open(filename, mode)

  • filename:filename 变量是一个包含了你要访问的文件名称的字符串值。
  • mode:mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
模式 描述
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
模式 r r+ w w+ a a+
+ + + +
+ + + + +
创建 + + + +
覆盖 + +
指针在开始 + + + +
指针在结尾 + +

例如创建一个新文件,并写入字符串进去,然后再读出来:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python3
# coding=utf-8
import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

#写入一段文字
f1.write("\nwrite words for testing write \nhello world\n")

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
p_str=f2.read()

f2.close()

print(p_str)

输出结果如下:

1
2
write words for testing write
hello world

1.2 f.readline()

f.readline() 会从文件中读取单独的一行。换行符为 ‘\n’。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python3
# coding=utf-8
import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

#写入一段文字
f1.write("write words for testing write \nhello world\n")

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
p_str=f2.readline()
p_str2=f2.readline(10)

f2.close()

print("读取一行: "+p_str)
print("读取10个字符: "+p_str2)

输出结果如下:

1
2
3
读取一行: write words for testing write

读取10个字符: hello worl

1.3 f.redlines()

f.readlines() 将返回该文件中包含的所有行。

如果设置可选参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python3
# coding=utf-8
import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

#写入一段文字
f1.write("write words for testing write. \nhello world\n")

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
p_str=f2.readlines()

f2.close()

print(p_str)

输出结果如下:

1
['write words for testing write. \n', 'hello world\n']

另一种方式是迭代一个文件对象然后读取每行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python3

import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

#写入一段文字
f1.write("write words for testing write. \nhello world\n")

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
for line in f2:
print(line)

f2.close()

输出结果如下:

1
2
3
write words for testing write.

hello world

1.4 f.write()

如果要写入一些不是字符串的东西, 那么将需要先进行转换:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/env python3

import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

a=["abcd",123]
b=str(a)
#写入一段文字
f1.write(b)

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
p_str=f2.read()

print(p_str)

f2.close()

输出结果如下:

1
['abcd', 123]

1.5 f.tell()

f.tell() 返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/usr/bin/env python3

import sys

#在当前路径下创建一个a.txt文件并打开写入模式
f1 = open(sys.path[0]+r"\a.txt","w")

#写入一段文字
f1.write("write words for testing write. \nhello world\n")

#关闭文件
f1.close()

#打开刚才创建的文件并使用读取模式
f2 = open(sys.path[0]+r"\a.txt","r")

#读取字符串
p_str=f2.readline()

#返回当前指针在文件中的位置
pos=f2.tell()

print(p_str)

print(pos)

f2.close()

输出结果如下:

1
2
3
write words for testing write.

33

1.6 f.seek()

如果要改变文件当前的位置, 可以使用 f.seek(offset, from_what) 函数。

from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如:

  • seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
  • seek(x,1) : 表示从当前位置往后移动x个字符
  • seek(-x,2):表示从文件的结尾往前移动x个字符

from_what 值为默认为0,即文件开头。下面给出一个完整的例子:

1
2
3
4
5
6
7
8
9
10
11
12
>>> f = open('a.txt', 'wb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2)
13
>>> f.read(1)
b'd'
>>>

1.7 with…as…

使用with…as…可以简化file的使用,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3

import sys

#在当前路径下创建一个a.txt文件并打开写入模式
with open(sys.path[0]+r"\a.txt","w") as f1:

#写入一段文字
f1.write("write words for testing write. \nhello world\n")

#打开刚才创建的文件并使用读取模式
with open(sys.path[0]+r"\a.txt","r") as f2:

#读取字符串
print(f2.read())

输出如下:

1
2
write words for testing write.
hello world

1.8 pickle 模块

python的pickle模块实现了基本的数据序列和反序列化。

通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。

通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。

基本接口:

1
pickle.dump(obj, file, [,protocol])

有了 pickle 这个对象, 就能对 file 以读取的形式打开:

1
x = pickle.load(file)

注解:从 file 中读取一个字符串,并将它重构为原来的python对象。

file: 类文件对象,有read()和readline()接口。

实例1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python3
import pickle

# 使用pickle模块将数据对象保存到文件
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

实例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python3
import pprint, pickle

#使用pickle模块从文件中重构python对象
pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()
文章作者: Sirius65535
文章链接: http://sirius.ink/2018/05/10/Python3基础知识10/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Sirius' Notes