标签:binary col 打开 测试 作文件 updating log ati blog
测试文件fansik内容如下:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
文件的操作方法:
def open(file, mode=‘r‘, buffering=None, encoding=None, errors=None, newline=None, closefd=True):
文件打开方式如下:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
‘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)
========= ===============================================================
文件读操作:
f = open(‘fansik‘, ‘r‘, encoding=‘utf8‘)
print(f.read())
f.close()
读取整个文件内容,结果如下:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
f = open(‘fansik‘, ‘r‘, encoding=‘utf8‘)
print(f.readline())
f.close()
读取整个文件第一行内容,结果如下:
This is line 1
f = open(‘fansik‘, ‘r‘, encoding=‘utf8‘)
print(f.readlines())
f.close()
读取整个文件内容,以列表方式显示,结果如下:
[‘This is line 1\n‘, ‘This is line 2\n‘, ‘This is line 3\n‘, ‘This is line 4\n‘, ‘This is line 5\n‘, ‘This is line 6‘]
同时操作多个文件(一下方式操作文件是可以不加f.close()):
number = 0
with open(‘fansik‘, ‘r‘, encoding=‘utf8‘) as f, open(‘fansik1‘, ‘w‘, encoding=‘utf8‘) as f1:
for line in f:
number += 1
if number == 5:
line = ‘‘.join([line.strip(), ‘fanjinbao\n‘])
f1.write(line)
fansik1文件内容如下:
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5fanjinbao
This is line 6
标签:binary col 打开 测试 作文件 updating log ati blog
原文地址:http://www.cnblogs.com/fansik/p/7644840.html