一、文件操作模式概述

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、所有功能

  1. class TextIOWrapper(_TextIOBase):
  2. """
  3. Character and line based layer over a BufferedIOBase object, buffer.
  4.  
  5. encoding gives the name of the encoding that the stream will be
  6. decoded or encoded with. It defaults to locale.getpreferredencoding(False).
  7.  
  8. errors determines the strictness of encoding and decoding (see
  9. help(codecs.Codec) or the documentation for codecs.register) and
  10. defaults to "strict".
  11.  
  12. newline controls how line endings are handled. It can be None, '',
  13. '\n', '\r', and '\r\n'. It works as follows:
  14.  
  15. * On input, if newline is None, universal newlines mode is
  16. enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  17. these are translated into '\n' before being returned to the
  18. caller. If it is '', universal newline mode is enabled, but line
  19. endings are returned to the caller untranslated. If it has any of
  20. the other legal values, input lines are only terminated by the given
  21. string, and the line ending is returned to the caller untranslated.
  22.  
  23. * On output, if newline is None, any '\n' characters written are
  24. translated to the system default line separator, os.linesep. If
  25. newline is '' or '\n', no translation takes place. If newline is any
  26. of the other legal values, any '\n' characters written are translated
  27. to the given string.
  28.  
  29. If line_buffering is True, a call to flush is implied when a call to
  30. write contains a newline character.
  31. """
  32. def close(self, *args, **kwargs): # real signature unknown
  33. pass
  34.  
  35. def detach(self, *args, **kwargs): # real signature unknown
  36. pass
  37.  
  38. def fileno(self, *args, **kwargs): # real signature unknown
  39. pass
  40.  
  41. def flush(self, *args, **kwargs): # real signature unknown
  42. pass
  43.  
  44. def isatty(self, *args, **kwargs): # real signature unknown
  45. pass
  46.  
  47. def read(self, *args, **kwargs): # real signature unknown
  48. pass
  49.  
  50. def readable(self, *args, **kwargs): # real signature unknown
  51. pass
  52.  
  53. def readline(self, *args, **kwargs): # real signature unknown
  54. pass
  55.  
  56. def seek(self, *args, **kwargs): # real signature unknown
  57. pass
  58.  
  59. def seekable(self, *args, **kwargs): # real signature unknown
  60. pass
  61.  
  62. def tell(self, *args, **kwargs): # real signature unknown
  63. pass
  64.  
  65. def truncate(self, *args, **kwargs): # real signature unknown
  66. pass
  67.  
  68. def writable(self, *args, **kwargs): # real signature unknown
  69. pass
  70.  
  71. def write(self, *args, **kwargs): # real signature unknown
  72. pass
  73.  
  74. def __getstate__(self, *args, **kwargs): # real signature unknown
  75. pass
  76.  
  77. def __init__(self, *args, **kwargs): # real signature unknown
  78. pass
  79.  
  80. @staticmethod # known case of __new__
  81. def __new__(*args, **kwargs): # real signature unknown
  82. """ Create and return a new object. See help(type) for accurate signature. """
  83. pass
  84.  
  85. def __next__(self, *args, **kwargs): # real signature unknown
  86. """ Implement next(self). """
  87. pass
  88.  
  89. def __repr__(self, *args, **kwargs): # real signature unknown
  90. """ Return repr(self). """
  91. pass
  92.  
  93. buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  94.  
  95. closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  96.  
  97. encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  98.  
  99. errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  100.  
  101. line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  102.  
  103. name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  104.  
  105. newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  106.  
  107. _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  108.  
  109. _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default

file

二、文件操作常用功能

注:默认以下操作都是基于下面文件操作的:

  1. 我越无所适从
  2. 越会事与愿违
  3. 在交错的时空
  4. 灵魂加速下坠
  5. Here we are, here we are, here we are

here_we_are

1、read()、readline()、readlines()的区别

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. info_file = open("here_we_are",encoding="utf-8") #默认读取模式
  5. print(info_file) #不加参数,直接打印
  6. #<_io.TextIOWrapper name='here_we_are' mode='r' encoding='utf-8'>
  7.  
  8. print(info_file.read()) #read参数,读取文件所有内容
  9. #我越无所适从
  10. #越会事与愿违
  11. #在交错的时空
  12. #灵魂加速下坠
  13. #Here we are, here we are, here we are
  14.  
  15. print(info_file.readline()) #readline,只读取文章中的一行内容
  16. #我越无所适从
  17.  
  18. print(info_file.readlines()) #readlines,把文章内容以换行符分割,并生成list格式,数据量大的话不建议使用
  19. #['我越无所适从\n', '越会事与愿违\n', '在交错的时空\n', '灵魂加速下坠\n', 'Here we are, here we are, here we are\n']

2、seek、tell光标

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #读取文件光标问题
  5. info_file = open("here_we_are",encoding="utf-8") #文件句柄
  6. data = info_file.read() #默认光标在起始位置,.read()读取完后,光标停留到文件末尾
  7. data2 = info_file.read() #data2读取到的内容为空
  8. print(data)
  9. print("--------",data2)
  10. info_file.close() #关闭文件
  11. #我越无所适从
  12. #越会事与愿违
  13. #在交错的时空
  14. #灵魂加速下坠
  15. #Here we are, here we are, here we are
  16. #--------
  17.  
  18. #用seek移动光标位置
  19. info_file = open("here_we_are",encoding="utf-8")
  20. print(info_file.tell()) #tell 获取当前的光标位
  21. print(info_file.readline().strip())
  22. print(info_file.readline().strip())
  23. print(info_file.readline().strip())
  24. print(info_file.tell())
  25. info_file.seek(0) #seek 移动光标到文件首部
  26. print(info_file.readline().strip()) #从文件首部开始打印
  27. info_file.close() #关闭文件
  28. #0
  29. #我越无所适从
  30. #越会事与愿违
  31. #在交错的时空
  32. #60
  33. #我越无所适从

3、文件循环

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #读取文件,并把第4行内容换成"-----我是分割线-------"
  5.  
  6. info_file = open("here_we_are",encoding="utf-8")
  7.  
  8. for index,line in enumerate(info_file.readlines()): #先把文件内容以行为分割生成列表,数据量大不能用
  9. if index == 3:
  10. print("-----我是分割线-------")
  11. continue
  12. print(line.strip())
  13.  
  14. count = 0
  15. for line in info_file: #建议使用方法,每读取一行,内存会把之前的空间清空,不会占用太多内存
  16. count +=1
  17. if count == 4:
  18. print("-----我是分割线-------")
  19. continue
  20. print(line.strip())
  21.  
  22. #我越无所适从
  23. #越会事与愿违
  24. #在交错的时空
  25. #-----我是分割线-------
  26. #Here we are, here we are, here we are 

4、flush 刷新

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #模拟安装进度条
  5. import sys,time #加载模块
  6.  
  7. for i in range(40):
  8. sys.stdout.write("#")
  9. sys.stdout.flush() #flush 强制刷新缓存到内存的数据写入硬盘
  10. time.sleep(0.1) 

5、truncate 截断

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. info_file = open("here_we_are","a") #非r、w模式
  5. info_file.seek(10)
  6. info_file.truncate(40)
  7. ###########文件内容###########
  8. #我越无所适从
  9. #越会事与愿违

注:truncate跟光标位置无关,从文件首部开始截取字符;如果是truncate(0)会把文件清空

6、with 语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

  1. with open('log','r') as f:
  2.  
  3. ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

  1. with open('log1') as obj1, open('log2') as obj2:
  2. pass  

7、r+ 读写  

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #读写模式
  5. info_file = open("here_we_are","r+",encoding="utf-8") #读写模式
  6. print(info_file.readline().strip())
  7. print(info_file.readline().strip())
  8. print(info_file.tell()) #查看读取两行后光标的位置
  9. info_file.write("\nfffffffff") #没有写入数据到光标的位置,而是以追加的模式写到了文件最后
  10. print(info_file.tell()) #查看写入数据后光标的位置
  11. print("----------\n",info_file.read()) #从上次读取的光标的位置开始读取到最后 注:新加入的内容不会打印
  12. info_file.close()
  13. ###########打印输出###########
  14. #我越无所适从 #注: 读写模式下文件以追加的方式进行写入
  15. #越会事与愿违
  16. #40
  17. #130
  18. #----------
  19. #在交错的时空
  20. #灵魂加速下坠
  21. #Here we are, here we are, here we are
  22. ###########文件内容###########
  23. #我越无所适从
  24. #越会事与愿违
  25. #在交错的时空
  26. #灵魂加速下坠
  27. #Here we are, here we are, here we are
  28. #fffffffff

由上面的实例可知,读写模式下写入是追加写的,没有添加到指定行,而是写到文件的末尾。   r+模式下真的只是读和追加写吗?!看看下面的程序

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #r+模式下对文件进行修改,文件修改在博客下面进行描述
  5. with open("here_we_are","r+",encoding="utf-8") as info_file:
  6. file_read = info_file.read()
  7. info_file.seek(0) #seek 光标移到文件首部
  8. new_file = file_read.replace("灵魂加速下坠","灵魂加速shangsheng") #把文件进行修改
  9. info_file.write(new_file) #写入到文件中
  10.  
  11. ############执行完后文件内容############
  12. #我越无所适从
  13. #越会事与愿违
  14. #在交错的时空
  15. #灵魂加速shangsheng
  16. #Here we are, here we are, here we are

看完上面代码你可能会想,擦,what are you 弄啥嘞?第一个程序不是说光标跟文件的写入文件没关系吗?不应该会把修改的内容添加到文件末尾吗?怎么替换了?(黑人问号脸),来看看下面的程序

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #r+模式下对文件进行修改,文件修改在博客下面进行详细描述
  5. with open("here_we_are","r+",encoding="utf-8") as info_file:
  6. file_read = info_file.read()
  7. info_file.seek(0) #seek 光标移到文件首部
  8. print(info_file.readline()) #新增一行文件打印,光标到第一行未
  9. new_file = file_read.replace("灵魂加速下坠","灵魂加速shangsheng") #把文件进行修改
  10. info_file.write(new_file) #写入到文件中
  11.  
  12. ############执行完后文件内容############
  13. #我越无所适从
  14. #越会事与愿违
  15. #在交错的时空
  16. #灵魂加速下坠
  17. #Here we are, here we are, here we are我越无所适从
  18. #越会事与愿违
  19. #在交错的时空
  20. #灵魂加速shangsheng
  21. #Here we are, here we are, here we are

这次在seek光标位置和对文件修改之间加了一条print,此刻会发现虽然光标在第一行尾末,但是新添加的内容写到了文件末尾,用的是追加模式。下面我们可以坐下总结了

总结:r+模式下,如果在.write()进行写入内容前,有print()输出,则要写的内容会从文件尾部开始写入,使用的是读、追加模式;如果在.write()进行写入内容前,是seek()移动光标,则要写的内容会从移动到的光标开始进行写入,会把原来的内容覆盖掉,而不是整体后移,这点要记住;如果在.write()进行写入内容前,既没有print()也没有seek()光标移动,这种情况之前想的的情况,就是r+读写模式能先写后读吗?r+模式下默认光标在文件的首部,此时会直接从文件开头进行写入,效果等同于seek(0)。关于最后一点,参考a+模式。

8、 w+ 写读

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #写读模式
  5. info_file = open("here_we_are2","w+",encoding="utf-8") #写读模式 此模式一般不用
  6.  
  7. info_file.write("我越无所适从\n") #向文件中写入四行内容
  8. info_file.write("越会事与愿违\n")
  9. info_file.write("在交错的时空\n")
  10. info_file.write("灵魂加速下坠\n")
  11. print(info_file.tell()) #打印光标 此时光标在写入文件末尾
  12. info_file.seek(0) #光标回到文件首部 如果不seek的话会从文件末尾打印,即为空
  13. print(info_file.tell())
  14. print(info_file.readline()) #打印第一行,光标回到第一行末尾
  15. info_file.write("------这一行应该写到第二行------") #理论上应该写在第一行的末尾后面
  16. info_file.close()
  17. ###########打印输出###########
  18. #80
  19. #0
  20. #我越无所适从
  21. ###########文件内容###########
  22. #我越无所适从
  23. #越会事与愿违
  24. #在交错的时空
  25. #灵魂加速下坠
  26. #------这一行应该写到第二行------

总结:读写模式一定要先写后读吗?能不能先读后写?  如果先读的话,由于用的是w+模式打开的文件,打开后会清空原文件内容,所有读取的到东西是空的。另W+模式后期用的很少,了解即可,包括a+追加读这种模式;另w+模式下,光标会跟随文件写入移到到文件末尾,不用seek移到光标的话,打印内容为空

注:w+模式下,关于.write()跟seek()和print()的关系与r+模式下是一样一样的。w+打开文件后先清空,然后追加写,如果.write()前有seek()的话会从光标位置覆盖写。

9、a+ 追加读

虽然a+不重要,但还是要通过下面的例子做下简单了解:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #a+ 追加写
  5. with open("here_we_are","a+",encoding="utf-8") as info_file: #追加写
  6. print(info_file.tell()) #打印光标 默认在文件尾部
  7. info_file.seek(0) #seek 光标移到文件首部
  8. info_file.write("----我是第一行------") #判断.write()与seek的关系
  9. ###########打印输出###########
  10. #117
  11. ###########执行后文件内容###########
  12. #我越无所适从
  13. #越会事与愿违
  14. #在交错的时空
  15. #灵魂加速下坠
  16. #Here we are, here we are, here we are----我是第一行------

总结:通过上面的程序可以得出,a+模式下光标位置为文件末尾,如果要print()的话要结合seek()进行使用;另外与r+、w+不同的是,.write()与seek()没有关系,只能写内容到文件末尾,一直都是追加模式!  

10、rb 二进制读

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #二进制读取
  5. info_file = open("here_we_are","rb") #二进制模式读取
  6. #应用场景:网络传输
  7. print(info_file.readline())
  8. print(info_file.readline())
  9. print(info_file.readline())
  10. #b'\xe6\x88\x91\xe8\xb6\x8a\xe6\x97\xa0\xe6\x89\x80\xe9\x80\x82\xe4\xbb\x8e\r\n'
  11. #b'\xe8\xb6\x8a\xe4\xbc\x9a\xe4\xba\x8b\xe4\xb8\x8e\xe6\x84\xbf\xe8\xbf\x9d\r\n'
  12. #b'\xe5\x9c\xa8\xe4\xba\xa4\xe9\x94\x99\xe7\x9a\x84\xe6\x97\xb6\xe7\xa9\xba\r\n'

11、wb 二进制写(ab也一样)

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4. #二进制写入
  5. info_file = open("here_we_are2","wb") #二进制模式写入
  6.                             #应用场景与rb相似
  7. info_file.write("我越无所适从\n".encode())    #对写入的字符串进行编码
  8. info_file.write("越会事与愿违\n".encode())
  9. info_file.close()

 12、文件的修改

文件修改方式:

  • 把文件读取到内存当中,对内存进行修改,把修改后的内容写入到原文件(旧内容被清空)
  • 如果在硬盘上直接写,会进行覆盖,硬盘上不能进行插入,原来的内容不会整体后移,而是直接覆盖掉
  • 把文件读取到内存当中,对内存进行修改,把修改的内容另存为新的文件(旧文件保留)

① 另存方式

  1. info_file = open("here_we_are","r",encoding="utf-8")
  2. new_file = open("here_we_are2","w",encoding="utf-8")
  3.  
  4. for line in info_file:
  5. if "灵魂加速下坠" in line:
  6. line = line.replace("灵魂加速下坠","灵魂加速shangsheng")
  7. new_file.write(line)
  8.  
  9. ##########执行后文件here_we_are2内容#########
  10. #我越无所适从
  11. #越会事与愿违
  12. #在交错的时空
  13. #灵魂加速shangsheng
  14. #Here we are, here we are, here we are

② r+模式

  1. #r+模式下对文件进行修改,
  2. with open("here_we_are","r+",encoding="utf-8") as info_file:
  3. file_read = info_file.read() #加载内容到内存,此时光标在文件末尾
  4. new_file = file_read.replace("灵魂加速下坠","灵魂加速shangsheng") #把文件进行修改
  5. info_file.truncate(0) #清空原文件,不会影响光标位置
  6. info_file.seek(0) #移动光标到文件首部,不做操作的话,新的内容会添加到之前光标的位置
  7. info_file.write(new_file) #修改的内容写入到文件中
  8.  
  9. ############执行完后文件内容############
  10. #我越无所适从
  11. #越会事与愿违
  12. #在交错的时空
  13. #灵魂加速shangsheng
  14. #Here we are, here we are, here we are

③ a+模式

  1. #a+模式下对文件进行修改,
  2. with open("here_we_are","a+",encoding="utf-8") as info_file:
  3. info_file.seek(0) #默认光标在文件末尾
  4. file_read = info_file.read() #加载内容到内存,此时光标在文件末尾
  5. new_file = file_read.replace("灵魂加速下坠","灵魂加速shangsheng") #把文件进行修改
  6. info_file.truncate(0) #清空原文件,不会影响光标位置
  7. info_file.seek(0) #移动光标到文件首部,不做操作的话,新的内容会添加到之前光标的位置
  8. info_file.write(new_file) #修改的内容写入到文件中
  9.  
  10. ############执行完后文件内容############
  11. #我越无所适从
  12. #越会事与愿违
  13. #在交错的时空
  14. #灵魂加速shangsheng
  15. #Here we are, here we are, here we are

三、练习

1、对文件实现替换功能

操作文件

  1. Somehow, it seems the love I knew was always the most destructive kind
  2. 不知为何,我经历的爱情总是最具毁灭性的的那种
  3. Yesterday when I was young
  4. 昨日当我年少轻狂
  5. The taste of life was sweet
  6. 生命的滋味是甜的
  7. As rain upon my tongue
  8. 就如舌尖上的雨露
  9. I teased at life as if it were a foolish game
  10. 我戏弄生命 视其为愚蠢的游戏
  11. The way the evening breeze
  12. 就如夜晚的微风
  13. May tease the candle flame
  14. 逗弄蜡烛的火苗
  15. The thousand dreams I dreamed
  16. 我曾千万次梦见
  17. The splendid things I planned
  18. 那些我计划的绚丽蓝图
  19. I always built to last on weak and shifting sand
  20. 但我总是将之建筑在易逝的流沙上
  21. I lived by night and shunned the naked light of day
  22. 我夜夜笙歌 逃避白昼赤裸的阳光
  23. And only now I see how the time ran away
  24. 事到如今我才看清岁月是如何匆匆流逝

yesterday

流程图

程序code

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4.  
  5. ##实现简单的替换功能
  6. with open("yesterday","r+",encoding="utf-8") as info_file: #with 方式打开文件yesterday
  7. old_data = input("Please input to modify content:")
  8. if old_data in info_file.read() and old_data != "": #判断输入的字符是否存在或不为空
  9. new_data = input("Please input to the content of the modified:")
  10. info_file.seek(0) #光标回到文件首部
  11. new_file = info_file.read().replace(old_data,new_data) #文件内容替换
  12. info_file.seek(0)
  13. info_file.truncate(0) #清空原文件
  14. info_file.write(new_file) #写入修改的内容到文件
  15. else:
  16. print("The content of the input does not exist")

2、修改haproxy配置文件

  • 可查询
  • 可增加
  • 可删除
  • 具体实现参考readme

操作文件:

  1. global
  2. log 127.0.0.1 local2
  3. daemon
  4. maxconn 256
  5. log 127.0.0.1 local2 info
  6. defaults
  7. log global
  8. mode http
  9. timeout connect 5000ms
  10. timeout client 50000ms
  11. timeout server 50000ms
  12. option dontlognull
  13.  
  14. listen stats :8888
  15. stats enable
  16. stats uri /admin
  17. stats auth admin:1234
  18.  
  19. frontend oldboy.org
  20. bind 0.0.0.0:80
  21. option httplog
  22. option httpclose
  23. option forwardfor
  24. log global
  25. acl www hdr_reg(host) -i www.oldboy.org
  26. use_backend www.oldboy.org if www
  27.  
  28. backend www.oldboy.org
  29. server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

haproxy

需知readme:

  1. # 实现简单的替换功能
  2.  
  3. ### 作者介绍:
  4. * authorlzl
  5. ### 博客地址:
  6. * http://www.cnblogs.com/lianzhilei/p/5722771.html(第八 集合)
  7. * http://www.cnblogs.com/lianzhilei/p/5749932.html
  8. * http://www.cnblogs.com/lianzhilei/p/5754069.html
  9. * http://www.cnblogs.com/lianzhilei/p/5754810.html
  10.  
  11. ### 实现效果:
  12. * 查看yesterday文件,输入想要替换的字符,然后输入新替换的字符,然后查看文件旧的字符被新的字符所替换
  13.  
  14. ### 运行环境:
  15. * Python3.0+
  16.  
  17. ### 目录结构:
  18.  
  19. Day3
  20. ├── 文件替换
  21. ├── file_relpace.py
  22. └── yesterday
  23. ├── file_relpace.png
  24. └── readme.txt
  25.  
  26. ### linux 运行说明:
  27.  
  28. * 上述文件都拷贝到同一级目录下
  29. * 加执行权限 chmod 755 file_relpace.py
  30. * 执行程序 python file_relpace.py

readme

流程图:

程序code:

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #-Author-Lian
  4.  
  5. def if_continue(): #定义函数if_continue() 提示用户是否继续操作
  6. if_cont = input("\n\33[34;1mDo you want to continue to operate on files【y】/【n】:\33[0m\n")
  7. if if_cont == "y":
  8. pass
  9. else:
  10. exit()
  11.  
  12. def info_message(options): #定义函数info_message() 提示用户操作信息
  13. print("\33[31;1mInfo of %s\33[0m".center(50,"-")%options)
  14.  
  15. with open("haproxy","a+",encoding="utf-8") as file_haproxy: #a+模式打开haproxy文件
  16. while True: #设置while循环
  17. dict_file = {}
  18. file_haproxy.seek(0) #移动光标到文件首部
  19. for line in file_haproxy:
  20. if "backend" in line and "use_backend" not in line: #提前文件中backend信息并生成字典dict_file
  21. dict_file[line.split()[1]]=file_haproxy.readline().strip()
  22.  
  23. print("File_Operations_Backend".center(50,"*"),"\n1\tQuery\n2\tAdd\n3\tDel\nq\tQuit")
  24. user_choice = input("\33[34;1mSelect the ID to operate:\33[0m") #让用户选择操作文件的模式
  25.  
  26. if user_choice == "1":
  27. info_query = input("\33[34;1mInput information to query:\33[0m")
  28. if info_query in dict_file.keys(): #判断输入的查询的信息是否存在
  29. info_message("Query")
  30. print(dict_file[info_query]) #如果查询的backend存在 打印查询的信息
  31. else: #否则提示没有查询到相关信息
  32. print("\33[31;1mError:No query to the corresponding information!\33[0m")
  33. if_continue()
  34.  
  35. elif user_choice == "2":
  36. info_add = input("\33[34;1mInput information to add:\33[0m")
  37. try: #判断输入的类型是否可以转换成字典格式
  38. dict_add = eval(info_add) #字符串转换成字典
  39. if dict_add["backend"] not in dict_file.keys(): #判断新增的信息没有存在于文件中
  40. dict_add_record = dict_add["record"] #把要添加的信息定义到变量file_add 中
  41. file_add = "backend %s\n\t\tserver %s weight %s maxconn %s\n"%(dict_add["backend"],
  42. dict_add_record["server"],dict_add_record["weight"],dict_add_record["maxconn"],)
  43. file_haproxy.write(file_add) #把新增的信息写到文件中
  44. info_message("Add") #打印增加成功
  45. print("\33[32;1mSuccessfully adding information backend %s to a file\33[0m"%(dict_add["backend"]))
  46. else: #如果已经存在 打印信息已经存在
  47. print("\33[31;1mError:Add the information already exists!\33[0m")
  48. if_continue()
  49. except Exception: #如果输入的字符不能转换为字典格式 提示错误
  50. print("\33[31;1mError:Please enter the dict format!\33[0m")
  51. if_continue()
  52.  
  53. elif user_choice == "3":
  54. info_del = input("\33[34;1mInput information to del:\33[0m")
  55. try: #判断输入的类型是否可以转换成字典格式
  56. dict_del = eval(info_del) #字符串转换成字典
  57. if dict_del["backend"] in dict_file.keys(): #判断要删除的信息有没有存在于文件中
  58. file_haproxy.seek(0)
  59. list_del = file_haproxy.readlines() #把文件信息写入列表list_del
  60. index = list_del.index("backend %s\n"%(dict_del["backend"])) #获取要删除信息的下标
  61. del list_del[index] #在列表中删除输入信息
  62. del list_del[index]
  63. file_haproxy.seek(0)
  64. file_haproxy.truncate(0) #文件清空
  65. for line in list_del: #把list_del内容写入到文件中
  66. file_haproxy.write(line)
  67. info_message("Del") #提示删除成功
  68. print("\33[32;1mSuccessfully delect information backend %s to a file\33[0m" % (dict_del["backend"]))
  69.  
  70. else: #如果要删除的信息不再文件中,打印信息不存在
  71. print("\33[31;1mError:Delect the information is not exists!\33[0m")
  72. if_continue()
  73. except Exception: #如果输入的字符不能转换为字典格式 提示错误
  74. print("\33[31;1mError:Please enter the dict format!\33[0m")
  75. if_continue()
  76.  
  77. elif user_choice == "q":
  78. print("\33[31;1mExit\33[0m".center(30,"-"))
  79. exit()
  80.  
  81. else:
  82. print("\33[31;1mError:Select the ID does not exist!\33[0m")

  

Python开发【第三章】:文件操作的更多相关文章

  1. 2 python第三章文件操作

    1.三元运算 三元运算又称三目运算,是对简单的条件语句的简写,如: 简单条件语句: if 条件成立: val = 1 else: val = 2 改成三元运算: val = 1 if 条件成立 els ...

  2. Python之路:Python 基础(三)-文件操作

    操作文件时,一般需要经历如下步骤: 打开文件 操作文件 一.打开文件 文件句柄 = file('文件路径', '模式') # 还有一种方法open 例1.创建文件  f = file('myfile. ...

  3. python基础(三)-- 文件操作

    一. 文件操作: 对文件操作流程 1.打开文件,得到文件句柄并赋值给一个变量 2.通过句柄对文件进行操作 3.关闭文件 现有文件如下 : Somehow, it seems the love I kn ...

  4. python开发_xml.etree.ElementTree_XML文件操作_该模块在操作XML数据是存在安全隐患_慎用

    xml.etree.ElementTree模块实现了一个简单而有效的用户解析和创建XML数据的API. 在python3.3版本中,该模块进行了一些修改: xml.etree.cElementTree ...

  5. Python基础(三)文件操作

    [对文件进行循环操作] fw = open('nhy','w') for line in fw: print('line:',line)   #直接循环文件对象,每次循环的时候就是取每一行的数据 fw ...

  6. 路飞学城-Python开发-第三章

    # 数据结构: # goods = [ # {"name": "电脑", "price": 1999}, # {"name&quo ...

  7. 基于Html5 Plus + Vue + Mui 移动App开发(三)-文件操作(读取、保存、更新数据)

      随着手机的发展,现在越来越多的人选择在手机上看书.无论是专业书籍.文学.英语还是网络小说,在手机上看新闻成了人们处理零碎时间的办法.在智能手机里安装一个资讯APP,可以随时.随地查看自己想看的资讯 ...

  8. 第三章 JavaScript操作BOM对象

    第三章   JavaScript操作BOM对象 一.window对象 浏览器对象模型(BOM)是javascript的组成之一,它提供了独立与浏览器窗口进行交换的对象,使用浏览器对象模型可以实现与HT ...

  9. (Python )格式化输出、文件操作、json

    本节学习Python的格式化输出,文件操作以及json的简单用法 1.格式化输出 将非字符串类型转换成字符串,可以使用函数:str() 或者repr() ,(这两个函数的区别目前我还没搞懂,求解答) ...

  10. ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇

    原文:ASP.NET自定义控件组件开发 第三章 为控件添加事件 前篇 第三章 为控件添加事件 好了,我们之前以前开发一个控件.而且也添加了属性,开发也很规范,但是那个控件还差最后一点:添加事件. 系列 ...

随机推荐

  1. linux下如何删除乱码文件

    首先执行ls -i命令,此时在文件前面会出现一个数字,这个数字是文件的节点号 接着,执行命令 find -inum 节点号 -delete 即可将乱码文件成功删除

  2. postman测试API

    首先创建环境变量 再次在请求参数中,可以应用环境变量,只需要在地址中引用环境变量即可 将返回的参数设置到环境变量中 如已经设置好环境变量,在认证中,选择Bearer Token,然后设置Token为环 ...

  3. GitHub OAuth 第三方登录示例教程

    这组 OAuth 系列教程,第一篇介绍了基本概念,第二篇介绍了获取令牌的四种方式,今天演示一个实例,如何通过 OAuth 获取 API 数据. 很多网站登录时,允许使用第三方网站的身份,这称为&quo ...

  4. Flutter移动电商实战 --(43)详细页_补充首页跳转到详细页

    首页轮播点击到详细页 修改我们轮播这里的代码:SwiperDiy这个类这里的代码 return InkWell( onTap: (){ Application.router.navigateTo(co ...

  5. Qt代码配色VS2015风格

    通过本文的方法可以将VS2015的深色主题界面应用到Qt上,对于喜欢VS代码风格配色的人应该会比较有用 效果图:  1. 设置IDE主题 为了配合vs深色的代码编辑背景,将Qt的主题也换成深色版本 2 ...

  6. C# WinForm快捷键设置技巧

    C# WinForm快捷键设置技巧 1.Alt+*(按钮快捷键) 按钮快捷键也为最常用快捷键,其设置也故为简单.在大家给button.label.menuStrip等其他控件的Text属性指定名称时, ...

  7. insmod某个内核模块时提示“Failed to find the folder holding the modules”如何处理?

    答: 创建/lib/modules/$(uname -r)目录,命令如下: mkdir /lib/modules/$(uname -r)

  8. 学习笔记——C++编程cin测试记录

    cin读取输入流,遇到空格会暂停,下次继续读入剩下的,+++. #include <iostream> using namespace std; int main() { cout< ...

  9. IOS APP开发入门案例

    1.创建新项目 2.设计布局,main.storyboard中,在控件库中 3.布局控件关联控制器 4.设置事件或者显示模式 5.编写代码: import UIKit class ViewContro ...

  10. Oracle查看表结构的方法【我】

    Oracle查看表结构的方法   方法一: 在命令窗口下输入   DESC table_name;  回车       方法二: 在sql窗口下   SELECT DBMS_METADATA.GET_ ...