Beng Dou

一只站在树上的鸟儿,从来不会害怕树枝断裂,因为它相信的不是树枝,而是它自己的翅膀。

导航

[ Python入门教程 ] Python文件基本操作

    本文将python文件操作实例进行整理,以便后续取用。

文件打开和创建

  Python中使用open()函数打开或创建文件。open()的声明如下:

open(name[, mode[, buffering]]) -> file object

其中,name表示文件名,mode表示文件打开模式。其中文件打开模式mode有如下类型

r 以只读的方式打开,常用
r+ 以读写的方式打开文件
w 以写方式打开文件,如果文件已存在,会先删再写,如果文件不存在,会创建新文件再写,常用
w+ 以读写方式打开文件,如果文件已存在,会先删再写,如果文件不存在,会创建新文件再写
a 以写方式打开文件,如果文件已存在,在文件末尾继续添加,如果文件不存在,会创建新文件再写,常用
a+ 以读写方式打开文件,如果文件已存在,在文件末尾继续添加,如果文件不存在,会创建新文件再写
b 以二进制模式打开文件,可与r、w、a、+结合使用
U 支持所有的换行符号。"\r""\n""\r\n"都表示换行

  open()函数返回的是一个file文件对象,可以对文件进行创建、打开、读写、关闭等操作。file对象常用方法如下:

fp.read([size]) 从文件中读取size个字节内容,作为字符串返回。如果不带参数,字符串形式返回文件全部内容
fp.readline([size]) 从文件中读取一行作为字符串返回,如果指定size,表示每行读取的字节数,依然要读完整行的内容。
fp.readlines([size]) 把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
fp.write(str) 把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq)   把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。
fp.close() 关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。  如果一个文件在关闭后还对其进行操作会产生ValueError
fp.seek(offset[,whence]) 将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
fp.tell() 返回文件指针当前位置,以文件的开头为原点
fp.next()  返回下一行内容,并将文件的指针移到下一行。
fp.flush()  把缓冲区的内容写入硬盘
fp.truncate([size]) 把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。

  说明:

  (1)read()、readline()、readlines()方法会把每行末尾的'\n'读取,并不会默认的把'\n'去掉。

  (2)write()、writelines()分别接收字符串、字符串列表为参数写入到文件中,换行符不会自动的加入,因此,需要显式的加入换行符。

Python读取/写入的典型方法

  简单示例说明Python读取文件的几种方式,具体如下:

with open('log.txt', 'r') as f:
    for line in f.readlines():
        ## do something
with open('log.txt', 'r') as f:
    for line in f:
      ## do something
with open('log.txt', 'r') as f:
    while True:
        line = f.readline()
        if not line:
          break
        ## do something
try:
    fp = open('log.txt', 'r')
    lines = fp.readlines()
    fp.close()
except IOError, msg:
    print '*** Cannot open', log.txt, ':', msg
    sys.exit(1)

 Python文件写入的方式如下:

with open('log.txt', 'w') as f:
    f.write('Hello, world!')
with open('log.txt', 'w') as f:
    f.writelines(["Hello", "World"])
f = open('log.txt', 'w')
f.write('Hello World\n')
f.writelines(["Hello", "World"])
f.close

操作文件常用类库

  os/os.path、sys、shutil、fileinput、configparser、linecache、

文件操作实例

1、查找指定目录下包含指定关键词的文件

#-*- coding:utf-8 -*-#

import os

current_dir = os.getcwd()
keyword = '.py'

for roots, dirs, files in os.walk(current_dir):
    for fn in files:
        if keyword in fn:
            print os.path.join(roots, fn)

os.system('pause')

2、根据指定关键字搜索文件内容并输出文件名

#-*- coding:utf-8 -*-#

import os

current_dir = os.getcwd()
keywords = ['Happy', 'New', 'Year']

flag = True
for roots, dirs, files in os.walk(current_dir):
    for fn in files:
        fp_abspath = os.path.join(roots, fn)
        fp = open(fp_abspath, 'r')
        fp_str = fp.read()
        for keyword in keywords:
            if keyword not in fp_str:
                flag = False
        if flag:
            print fp_abspath
        fp.close()
        
os.system('pause')

3、实现将指定目录下的文件内容合并到一个文件。

#-*- coding:utf-8 -*-#

import os
import fileinput

current_dir = os.getcwd()
file_lists = []
combine_file = 'combine_files.txt'

if os.path.exists(combine_file):
    os.remove(combine_file)

for roots, dirs, files in os.walk(current_dir):
    for fn in files:
        if fn.endswith('.txt'):
            file_lists.append(os.path.join(roots, fn))
print file_lists
for eachLine in fileinput.input(files=file_lists, inplace=True):
    if fileinput.isfirstline():
        #print fileinput.filename()
        print os.path.split(fileinput.filename())[1]
    print eachLine,

fw = open(combine_file, 'w')
    
for fn in file_lists:
    fp = open(fn, 'r')
    fw.writelines(fp.readlines())
    fp.close()

fw.close()

4、将指定文件内容按行拆分,每行单独写入一个文件。并在每行的起始处标记行号。

# -*- coding: utf-8 -*-

import os
import sys

filename = 'temp_1.txt'
filename_prefix = os.path.splitext(filename)[0]
filename_posfix = os.path.splitext(filename)[1]
    
if not os.path.exists(filename):
    print "THe %s file not exist,please check" % (filename,)
    
fp = open(filename, 'r')
line_no = 1
for eachLine in fp.readlines():
    filename_eachLine = filename_prefix + '_Line_' + str(line_no) + filename_posfix
    fw_eachLine = open(filename_eachLine, 'w')
    fw_eachLine.write('Line ' + str(line_no) + ': ' + eachLine.rstrip())
    fw_eachLine.close()
    line_no += 1
fp.close()
print "End the script,exit"

 

posted on 2018-03-17 21:01  锅边糊  阅读(642)  评论(0编辑  收藏  举报