Python基础-文件的基本操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python基础-文件的基本操作相关的知识,希望对你有一定的参考价值。
测试文件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
以上是关于Python基础-文件的基本操作的主要内容,如果未能解决你的问题,请参考以下文章