码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础-文件的基本操作

时间:2017-10-10 13:05:51      阅读:234      评论:0      收藏:0      [点我收藏+]

标签: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

Python基础-文件的基本操作

标签:binary   col   打开   测试   作文件   updating   log   ati   blog   

原文地址:http://www.cnblogs.com/fansik/p/7644840.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!