您的位置:首页 > 编程语言 > Python开发

Python开发【第三章】:文件操作

2016-08-08 16:31 459 查看

一、文件操作模式[b]概述[/b]

1、打开文件的模式:

r, 只读模式【默认】

w,只写模式【不可读;不存在则创建;存在则删除内容;】

a, 追加模式【不可读;不存在则创建;存在则只追加内容;】

2、"+" 同时读写某个文件:

r+,可读写文件。【可读;可写;可追加】

w+,写读

a+,追加读

3、"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

rU

r+U

4、"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

rb

wb

ab

5、所有功能

# 实现简单的替换功能

### 作者介绍:
* author:lzl
### 博客地址:
* http://www.cnblogs.com/lianzhilei/p/5722771.html(第八 集合)
* http://www.cnblogs.com/lianzhilei/p/5749932.html * http://www.cnblogs.com/lianzhilei/p/5754069.html * http://www.cnblogs.com/lianzhilei/p/5754810.html 
### 实现效果:
* 查看yesterday文件,输入想要替换的字符,然后输入新替换的字符,然后查看文件旧的字符被新的字符所替换

### 运行环境:
* Python3.0+

### 目录结构:

Day3
├── 文件替换
│   ├── file_relpace.py
│   └── yesterday
│   ├── file_relpace.png
│   └── readme.txt

### linux 运行说明:

* 上述文件都拷贝到同一级目录下
* 加执行权限 chmod 755  file_relpace.py
* 执行程序   python  file_relpace.py


readme
流程图:



程序code:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
#-Author-Lian

def if_continue():                      #定义函数if_continue() 提示用户是否继续操作
if_cont = input("\n\33[34;1mDo you want to continue to operate on files【y】/【n】:\33[0m\n")
if if_cont == "y":
pass
else:
exit()

def info_message(options):              #定义函数info_message() 提示用户操作信息
print("\33[31;1mInfo of %s\33[0m".center(50,"-")%options)

with open("haproxy","a+",encoding="utf-8") as file_haproxy:       #a+模式打开haproxy文件
while True:                                                    #设置while循环
dict_file = {}
file_haproxy.seek(0)                                        #移动光标到文件首部
for line in file_haproxy:
if "backend" in line and "use_backend" not in line: #提前文件中backend信息并生成字典dict_file
dict_file[line.split()[1]]=file_haproxy.readline().strip()

print("File_Operations_Backend".center(50,"*"),"\n1\tQuery\n2\tAdd\n3\tDel\nq\tQuit")
user_choice = input("\33[34;1mSelect the ID to operate:\33[0m")  #让用户选择操作文件的模式

if user_choice == "1":
info_query = input("\33[34;1mInput information to query:\33[0m")
if info_query in dict_file.keys():     #判断输入的查询的信息是否存在
info_message("Query")
print(dict_file[info_query])        #如果查询的backend存在 打印查询的信息
else:                                  #否则提示没有查询到相关信息
print("\33[31;1mError:No query to the corresponding information!\33[0m")
if_continue()

elif user_choice == "2":
info_add = input("\33[34;1mInput information to add:\33[0m")
try:                                    #判断输入的类型是否可以转换成字典格式
dict_add = eval(info_add)           #字符串转换成字典
if dict_add["backend"] not in dict_file.keys():     #判断新增的信息没有存在于文件中
dict_add_record = dict_add["record"]             #把要添加的信息定义到变量file_add 中
file_add = "backend %s\n\t\tserver %s weight %s maxconn %s\n"%(dict_add["backend"],
dict_add_record["server"],dict_add_record["weight"],dict_add_record["maxconn"],)
file_haproxy.write(file_add)           #把新增的信息写到文件中
info_message("Add")                     #打印增加成功
print("\33[32;1mSuccessfully adding information backend %s to a file\33[0m"%(dict_add["backend"]))
else:                                       #如果已经存在 打印信息已经存在
print("\33[31;1mError:Add the information already exists!\33[0m")
if_continue()
except Exception:                           #如果输入的字符不能转换为字典格式 提示错误
print("\33[31;1mError:Please enter the dict format!\33[0m")
if_continue()

elif user_choice == "3":
info_del = input("\33[34;1mInput information to del:\33[0m")
try:                                         #判断输入的类型是否可以转换成字典格式
dict_del = eval(info_del)                    #字符串转换成字典
if dict_del["backend"] in dict_file.keys():       #判断要删除的信息有没有存在于文件中
file_haproxy.seek(0)
list_del = file_haproxy.readlines()         #把文件信息写入列表list_del
index = list_del.index("backend %s\n"%(dict_del["backend"]))  #获取要删除信息的下标
del list_del[index]                         #在列表中删除输入信息
del list_del[index]
file_haproxy.seek(0)
file_haproxy.truncate(0)                    #文件清空
for line in list_del:                       #把list_del内容写入到文件中
file_haproxy.write(line)
info_message("Del")                         #提示删除成功
print("\33[32;1mSuccessfully delect information backend %s to a file\33[0m" % (dict_del["backend"]))

else:                                           #如果要删除的信息不再文件中,打印信息不存在
print("\33[31;1mError:Delect the information is not exists!\33[0m")
if_continue()
except Exception:                               #如果输入的字符不能转换为字典格式 提示错误
print("\33[31;1mError:Please enter the dict format!\33[0m")
if_continue()

elif user_choice == "q":
print("\33[31;1mExit\33[0m".center(30,"-"))
exit()

else:
print("\33[31;1mError:Select the ID does not exist!\33[0m")


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: