Python中文件操作

一、文件打开操作

1、文件操作步骤:

(1)打开文件模式:

f =open(“db”,’a’)    #文件追加

       f = open(“db”,’r’)    #只读操作(默认模式)

       f = open(“db”,’w’)    #只写操作,会先清空原文件

       f = open(“db”,’x’)    #文件存在,会报错,不存在创建并只写

       f = open(“db”,’rx|a|w’)  #以二进制的方式只读或只写文件

(2)操作文件:通过源码查看功能

(3)关闭文件:f.close()

2、文件操作:

(1)读取操作:

f = open('db','r')             #以只读的方式打开文件db
data = f.read()                #读取文件中的内容,并赋值为data
print(data,type(data))
f.close()                     #如果出现enconding乱码,则需要注意字符的的编码

(2)以二进制的方式读取操作:

f = open("db", 'rb')         #不让Python处理,直接读取字节
data = f.read()
print(data, type(data))

(3)以二进制的方式追加操作:

f = open('db', 'ab')        #往里面写字节,如果写字符串会报错
#f.write("hello")
f.write(bytes("hell0", encoding="utf-8"))     #直接往里面写字节
f.close()

3.”+”同时读写操作某个文件

(1)、文件操作说明

r+, 读写   会在指针当前位置处向后覆盖

w+, 写读     先清空文件,再去写

x+, 写读 

a+, 写读  永远会写在最后

(2)、操作

f = open('db', 'r+', encoding="utf-8")  #如果打开模式无b,则读取按照字符读取
data = f.read(1)    #读取第一个字符
print(data)

print(f.tell())        #获取当前指针的位置
f.seek(1)          #调整指针的位置,指针的位置在读到哪儿在哪儿
f.write("刘")        #当前指针位置开始向后覆盖,如果指针位置是中文,可能会乱码
f.close()

4、文件打开后其他常用操作

(1)read()    #无参数,读全部;有参数,”b”按字节,无”b”,按字符

(2)tell()    #获取当前指针的位置(跟打开方式无关,永远按字节)

(3)seek()    #指针跳转到指定位置(跟打开方式无关,永远按字节)

(4)write()   #写数据(跟打开方式有关)

(5)close()   #关闭文件

(6)fileno    #文件描述符

(7)flush()   #强刷,将内存中的buffer保存到硬盘中去

(8)readline() #仅读取一行

(9)trunce() #截断,指针后面的清空

(10)truncate(n)    #截断,截取n个字符,放入源文件中

(11)for循环文件对象 f =open(‘db’,’r’)

forline in f:

  print(line)

5、案例:实现进度条

#!/usr/bin/envpython
# -*-coding:utf-8 -*-
#Author:dayi123
import sys,time
for i in range(100):
    sys.stdout.write("#")     #将内容输出到屏幕
    sys.stdout.flush()         #每输出一次刷新一次
     time.sleep(0.5)

二、关闭文件

1、文件关闭操作

(1)close()  #关闭文件

(2)with open(‘xb’) as f:    #打开并操作文件,操作完关闭,

  pass

withopen(‘db1’,’r’) as f1, open(“db2”,’w’) as f2:

#with可以同时打开两个文件

  pass

2、文件关闭操作案例

例1:将”db1”中前十行复制到”db2”中

with open('db1', 'r', encoding="utf-8")as f1, open('db2','w',encoding="utf-8")as f2:
    for line in f1:
        new_str = line.replace("dayi123",'st')
        f2.write(new_str)

3、文件操作案例——修改配置文件

def fetch(backend):                      #定义一个查功能的函数
    result = []                          #定义一个空列表
    with open('ha.conf', 'r') as f:         #以只读的方式打开ha.conf
        flag = False                    #定义一个标示符,并赋值为Fals
        for line in f:
            if line.strip().startswith('backend') and line.strip() == "backend " + backend:
                flag = True             #如果文件匹配到文件中的行,将falg的值设置为True
                continue               #跳出本次循环继续
            if flag and line.strip().startswith('backend'):
                break                  #如果匹配到下一个‘backend’则终止此次循环
            if flag and line.strip():
               result.append(line.strip()) #如果flag为true并且当前匹配到的行不是空行,则将当前的行添加到列表中
    return result

def add(backend, record):          #思路1
    result = fetch(backend)
    if not result:                # 无backend
        with open('ha.conf', 'r')as old, open("new.conf", 'w') as new:
            for line in old:
                new.write(line)
            new.write("\nbackend " + backend + "\n")    #在最后添加backend和record
            new.write(" " * 8 +record + "\n")
    else:      # 有backend
        if record in result:       #backend存在,record存在
            # 记录record
            pass
        else:                      #backend存在,record不存在
            result.append(record)  #将record添加到内存中即result列表中
            with open('ha.conf', 'r') as old, open('new.conf', 'w') as new:
                continue_flag = False
                for line in old:

                    if line.strip().startswith('backend') and line.strip() == "backend " + backend:
                        continue_flag = True     # 定义一个标示符,并赋值为True
                        new.write(line)          #将当前行写入new.conf
                        for temp in result:
                            new.write(" " * 8 + temp + "\n")
                        continue

                    if continue_flag and line.strip().startswith('backend'):
                        continue_flag = False               #如果找到下一个backend,将conti_flag标记为false
                    if continue_flag:
                        pass
                    else:
                        new.write(line)
ret = fetch("    #查询 
print(ret)

add('dayi.dayi123.org', "server 100.1.7.10 100.1.7.10 weight 20 maxconn 3000")#添加或修改

配置文件如下(ha.conf):

global
        log 127.0.0.1 local2
        daemon
        maxconn 256
        log 127.0.0.1 local2 info
defaults
        log global
        mode http
        timeout connect 5000ms
        timeout client 50000ms
        timeout server 50000ms
        option  dontlognull

listen stats :8888
        stats enable
        stats uri       /admin
        stats auth      admin:1234

frontend oldboy.org
        bind 0.0.0.0:80
        option httplog
        option httpclose
        option  forwardfor
        log global
        acl www hdr_reg(host) -i www.oldboy.org
        use_backend www.oldboy.org if www

backend www.dayi123.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

三、python2.7中文件操作

1、文件操作

#read
f = file("hah", "r")      #以只读的方式打开文件
for line in f.readlines():
    print line,
f.close()
#write                     #往文件里写内容,之前写的内容会被清除
f = file("er", "w")
f.write("this is the first line\n")
f.write("this is the second line\n")
f.close()
#append                    #往文件里面追加内容
f = file("er","a")
f.write("niani ,ren a ,zong shi zhe yang,dengshiqule cai houhui\n")

2、文件操作举例(使用参数替换文件中的内容)

import sys
if '-r' in sys.argv:
    rep_argv_pos = sys.argv.index('-r')
    find_str = sys.argv[rep_argv_pos +1]
    new_str = sys.argv[rep_argv_pos +2]
f = file('passwd','r+')
while True:
    line = f.read()
    print "==>",f.tell()
    if find_str in line:
        print '--->cur pos:',f.tell(),len(line)
        last_line_pos = f.tell() - len(line)
        f.seek(last_line_pos)
        print '--->',f.tell()
        new_line = line.replace(find_str, new_str)
        f.write(new_line)
        f.write(new_line)
        break
f.close()

替换方法(在Linux系统下):python2.7 –rdayi123 DAYI