zoukankan      html  css  js  c++  java
  • 如何优雅的打开文件

    文件的基本操作

    这里讲主要是讲到如何打开文件,设置文件的打开权限以及方式

    打开文件

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

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

    • rU
    • r+U

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

    • rb
    • wb
    • ab

    Table 文件对象方法

    方法 描述
    f.close() 关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。
    f.fileno() 获得文件描述符,是一个数字
    f.flush() 刷新输出缓存
    f.isatty() 如果文件是一个交互终端,则返回True,否则返回False。
    f.read([count]) 读出文件,如果有count,则读出count个字节。
    f.readline() 读出一行信息。
    f.readlines() 读出所有行,也就是读出整个文件的信息。
    f.seek(offset[,where]) 把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值 ;1表示当前位置;2表示文件结尾。
    f.tell() 获得文件指针位置。
    f.truncate([size]) 截取文件,使文件的大小为size。
    f.write(string) 把string字符串写入文件。
    f.writelines(list) 把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。

    read(3)代表读取3个字符,其余的文件内光标移动是以字节为单位,如:seek,tell,read,truncate

    f.flush()      #讲文件内容从内存刷到硬盘(python3.x)

    f.closed       #文件如果关闭则返回True

    f.encoding   #查看使用open打开文件的编码

    f.tell()         #查看文件处理当前的光标位置

    f.seek(3)     #从开头开始算,将光标移动到第三个字节

    f.truncate(10) #从开头开始算,将文件只保留从0-10个字节的内容,文件必须以写方式打开,但是w和w+除外

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    文件的打开语法一般是open()语句

    1 f  = open("txt","r") #用只读方式打开文件名为txt f变量作为文件的操作对象
    2 
    3 f.close() #文件打开后要记得关闭 

    注意 使用只读'r'打开文件时是从文件头开始读取内容。使用追加'a'打开文件时是从文件末尾开始写入内容。在使用只写'w'往文件中写入文件时,是先创建一个新的文件将写的内容写到新的文件中再覆盖旧的文件,这样原文件中的内容都会消失。

    练习

    编写登陆接口

    • 输入用户名密码
    • 认证成功后显示欢迎信息
    • 输错三次后锁定

    锁定的用户名单

    张三
    李四
    lockedname

    登录的用户名单

    尼古拉斯赵四 123
    亚历山大王二 456
    login
     1 #Auther: Xiaoliuer Li
     2 
     3 import sys
     4 
     5 f = open("lockedname", "r", encoding="utf-8")       #打开被锁定的用户名单 从头开始读取文件
     6 f1 = open("login","r",encoding="utf-8")       #打开登录用户的名单
     7 
     8 
     9 
    10 
    11 i = 0              #设置变量来控制循环次数
    12 while i < 3:
    13 
    14     user = input("请输入用户名:")
    15     for line in f:                                  #在被锁定的名单搜索用户名
    16         if user == line.strip():
    17             print("用户%s已经被锁定"%user)
    18             sys.exit()   #跳出整个程序
    19 
    20     if len(user) == 0:
    21         print("用户名不能为空 请重新输入")
    22         continue
    23 
    24     passwd = input("请输入密码:")
    25     T = False                         #设置变量来跳出循环
    26     for line in f1:
    27         if line.split()[0] == user and line.split()[1] == passwd:
    28             print("success!")
    29             T = True
    30             break
    31 
    32     if T == False:                 #当变量为输入的用户和密码错误时进入此循环并使次数自增一次
    33         if i < 2:
    34             print('您的用户或密码有误,请重新输入!')
    35         i += 1
    36 
    37     else:
    38         print("欢迎用户 %s 来到登录系统" % user)
    39         break
    40 
    41 else:
    42     f = open("lockedname", "a", encoding="utf-8")    #在文件末尾追加用户名
    43     print("你的用户%s已经被锁定!"%user)             #将三次输错的用户名写进名单
    44     f.write("
    " + user)
    45 
    46 
    47 f.close()
    48 f1.close()
     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 事到如今我才看清岁月是如何匆匆流逝
    25 Yesterday when I was young
    26 昨日当我年少轻狂
    27 So many lovely songs were waiting to be sung
    28 有那么多甜美的曲儿等我歌唱
    29 So many wild pleasures lay in store for me
    30 有那么多肆意的快乐等我享受
    31 And so much pain my eyes refused to see
    32 还有那么多痛苦 我的双眼却视而不见
    33 I ran so fast that time and youth at last ran out
    34 我飞快地奔走 最终时光与青春消逝殆尽
    35 I never stopped to think what life was all about
    36 我从未停下脚步去思考生命的意义
    37 And every conversation that I can now recall
    38 如今回想起的所有对话
    39 Concerned itself with me and nothing else at all
    40 除了和我相关的 什么都记不得了
    41 The game of love I played with arrogance and pride
    42 我用自负和傲慢玩着爱情的游戏
    43 And every flame I lit too quickly, quickly died
    44 所有我点燃的火焰都熄灭得太快
    45 The friends I made all somehow seemed to slip away
    46 所有我交的朋友似乎都不知不觉地离开了
    47 And only now I'm left alone to end the play, yeah
    48 只剩我一个人在台上来结束这场闹剧
    49 Oh, yesterday when I was young
    50 噢 昨日当我年少轻狂
    51 So many, many songs were waiting to be sung
    52 有那么那么多甜美的曲儿等我歌唱
    53 So many wild pleasures lay in store for me
    54 有那么多肆意的快乐等我享受
    55 And so much pain my eyes refused to see
    56 还有那么多痛苦 我的双眼却视而不见
    57 There are so many songs in me that won't be sung
    58 我有太多歌曲永远不会被唱起
    59 I feel the bitter taste of tears upon my tongue
    60 我尝到了舌尖泪水的苦涩滋味
    61 The time has come for me to pay for yesterday
    62 终于到了付出代价的时间 为了昨日
    63 When I was young
    64 当我年少轻狂
    示例文本

    python文件操作 

    seek():移动文件读取指针到指定位置(按照字节读取)

    tell():返回文件读取指针的位置(按照字符读取)

    用with语句实现,文件自动关闭

    1 with open("test","r",encoding="utf-8") as f:
    2     print(f.tell()) #按字符计算
    3     print(f.readline())#按字符进行读取
    4     print(f.readline())
    5     print(f.tell())
    6 
    7     f.seek(0) #按照字节计算
    8     f.seek(10)#返回到第十个字节 文章是中文可能会报错 每个中文是三个字节
    9     print(f.readline())

    name():打印文件名称

    1 with open("test","r",encoding="utf-8") as f:
    2     print(f.name)

    更改文件内容

    先创建一个新文件,再读取文件内容,再更改其中某一行内容

    1 with open("test","r",encoding="utf-8") as f ,
    2         open("test2","w",encoding="utf-8") as f2: #同时打开两个文件
    3     for line in f:
    4         if "肆意的快乐等我享受" in line:
    5             line = line.replace("肆意的快乐等我享受", "肆意的快乐等Alex享受")
    6         f2.write(line)

     最后放个大招,是之前的一个作业。

    HAproxy配置文件操作:
    1. 根据用户输入输出对应的backend下的server信息
    2. 可添加backend 和sever信息
    3. 可修改backend 和sever信息
    4. 可删除backend 和sever信息
    5. 操作配置文件前进行备份
    6 添加server信息时,如果ip已经存在则修改;如果backend不存在则创建;若信息与已有信息重复则不操作配置文件

      1 #Auther: Xiaoliuer Li
      2 
      3 import os
      4 
      5 
      6 def fetch(data):
      7     backend_data = "backend %s" % data  #查找匹配到这行,找到对应的server记录,用字符串拼接的方法
      8     record_list = []  # 定义一个空列表
      9     with open('haproxy.conf', 'r') as f:  # 打开haproxy.conf配置文件
     10         tag = False  # 报警器不响
     11         for line in f:  # 去查找文件
     12             if line.strip() == backend_data:  # 把文件的每一行
    去掉,才能进行比较,就找到这行backend www.oldboy1.org
     13                 tag = True  # 找到人就响警报
     14                 continue  # 就跳出这个循环
     15             if tag and line.startswith('backend'):  # 找到下一行的backend,backend www.oldboy2.org 我们就跳出循环
     16                 break
     17             if tag and line:  # 相当于警报响了
     18                 record_list.append(
     19                     line.strip())  # 找到了server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33333333333,就要把他加到列表中
     20         for line in record_list:
     21             print(line)  # 给用户打印找到的信息
     22         return record_list  # 给用户返回处理的信息
     23 
     24 
     25 def add(data):
     26     backend = data['backend'] #创建变量保存用户输入的网址
     27     record_list = fetch(backend) #在fetch函数中查找有没有出现相同的网址
     28     # 用变量来储存用户输入的信息
     29     current_record = "server %s %s weight %s maxconn %s" % (data['record']['server'],
     30                                                             data['record']['server'],
     31                                                             data['record']['weight'],
     32                                                             data['record']['maxconn'])
     33     # 用变量记录所要写入的第一行的内容
     34     backend_data = "backend %s" % backend
     35 
     36     # 在文件中找不到所要找的网址就在文件后面添加
     37     if not record_list:
     38         # 将用户输入的信息以列表的形式储存
     39         record_list.append(backend_data)
     40         record_list.append(current_record)
     41         with open('haproxy.conf', 'r') as read_file, 
     42                 open('haproxy_new.conf', 'w') as write_file:
     43             for r_line in read_file:
     44                 write_file.write(r_line)
     45 
     46             for new_line in record_list:
     47                 if new_line.startswith('backend'):
     48                     write_file.write(new_line + '
    ')
     49                 else:
     50                     write_file.write("%s%s
    " % (' ' * 8, new_line))
     51     # 当文件中可以找到网址时,就创建一个新的文件边读边写
     52     else:
     53         # 此时record_list中含有原文件中的内容,将网址信息插到表头再将新的信息添加到表中
     54         record_list.insert(0, backend_data)
     55         record_list.append(current_record)
     56         with open('haproxy.conf', 'r') as read_file, 
     57                 open('haproxy_new.conf', 'w') as write_file:
     58             tag = False
     59             has_write = False
     60             for r_line in read_file:  #遍历文件
     61                 if r_line.strip() == backend_data:#当在文件中找网址时写信息
     62                     tag = True
     63                     continue
     64                 if tag and r_line.startswith('backend'):
     65                     tag = False
     66                 if not tag:
     67                     write_file.write(r_line)
     68                 else:
     69                     if not has_write:
     70                         for new_line in record_list:
     71                             if new_line.startswith('backend'):
     72                                 write_file.write(new_line + '
    ')
     73                             else:
     74                                 write_file.write("%s%s
    " % (' ' * 8, new_line))
     75                         has_write = True
     76     os.rename('haproxy.conf', 'haproxy_bat.conf')
     77     os.rename('haproxy_new.conf', 'haproxy.conf')
     78     os.remove('haproxy_bat.conf')
     79 
     80 
     81 def remove(data):
     82     backend = data['backend']
     83     record_list = fetch(backend)
     84     current_record = "server %s %s weight %s maxconn %s" % (data['record']['server'],
     85                                                             data['record']['server'],
     86                                                             data['record']['weight'],
     87                                                             data['record']['maxconn'])
     88     backend_data = "backend %s" % backend
     89     if not record_list and current_record not in record_list:
     90         print('33[33:[1m无此条记录33[0]')
     91         return
     92     else:
     93         # 将用户输入backend信息列表头,并将输入的server信息去除,然后将新的列表中我数据写到文件中去
     94         record_list.insert(0, backend_data)
     95         record_list.remove(current_record)
     96         with open('haproxy.conf', 'r') as read_file, 
     97                 open('haproxy_new.conf', 'w') as write_file:
     98             tag = False
     99             has_write = False
    100             for r_line in read_file:
    101                 if r_line.strip() == backend_data:
    102                     tag = True
    103                     continue
    104                 if tag and r_line.startswith('backend'):
    105                     tag = False
    106                 if not tag:
    107                     write_file.write(r_line)
    108                 else:
    109                     if not has_write:
    110                         for new_line in record_list:
    111                             if new_line.startswith('backend'):
    112                                 write_file.write(new_line + '
    ')
    113                             else:
    114                                 write_file.write("%s%s
    " % (' ' * 8, new_line))
    115                         has_write = True
    116     os.rename('haproxy.conf', 'haproxy_bat.conf')
    117     os.rename('haproxy_new.conf', 'haproxy.conf')
    118     os.remove('haproxy_bat.conf')
    119 
    120 
    121 # {'backend':'www.oldboy1.org11111','record':{'server':'11.100.200.1','weight':22,'maxconn':200}}
    122 
    123 
    124 def change(data):
    125     backend = data[0]['backend']  # 找到要修改的第一条记录
    126     record_list = fetch(backend)
    127     # 用户输入的信息时一列表形式存储的两个字典,通过索引找到值
    128     old_record = "server %s %s weight %s maxconn %s" % (data[0]['record']['server'],
    129                                                         data[0]['record']['server'],
    130                                                         data[0]['record']['weight'],
    131                                                         data[0]['record']['maxconn'])
    132 
    133     new_record = "server %s %s weight %s maxconn %s" % (data[1]['record']['server'],
    134                                                         data[1]['record']['server'],
    135                                                         data[1]['record']['weight'],
    136                                                         data[1]['record']['maxconn'])
    137     backend_data = "backend %s" % backend
    138     if not record_list and old_record not in record_list:  # 判断这个文件在原文件中不存在
    139         print('33[33:[1m无此内容33[0]')
    140         return
    141     else:
    142         record_list.insert(0, backend_data)  # 判断文件存在原文件中
    143         index = record_list.index(old_record)  # 求出这个索引
    144         record_list[index] = new_record  # 用新的记录,替换掉旧记录
    145         with open('haproxy.conf', 'r') as read_file, 
    146                 open('haproxy_new.conf', 'w') as write_file:
    147             tag = False
    148             has_write = False
    149             for r_line in read_file:
    150                 if r_line.strip() == backend_data:
    151                     tag = True
    152                     continue
    153                 if tag and r_line.startswith('backend'):
    154                     tag = False
    155                 if not tag:
    156                     write_file.write(r_line)
    157                 else:
    158                     if not has_write:
    159                         for new_line in record_list:
    160                             if new_line.startswith('backend'):
    161                                 write_file.write(new_line + '
    ')
    162                             else:
    163                                 write_file.write("%s%s
    " % (' ' * 8, new_line))
    164                         has_write = True
    165     os.rename('haproxy.conf', 'haproxy_bat.conf')
    166     os.rename('haproxy_new.conf', 'haproxy.conf')
    167     os.remove('haproxy_bat.conf')
    168 
    169 
    170 if __name__ == '__main__': #主函数
    171     print("""
    172     1:查询  #fetch
    173     2:添加  #add
    174     3:删除  #remove
    175     4: 修改  #change
    176     5:退出  #exit
    177     """)
    178 
    179     choice_list =[fetch,add,remove,change] #将函数名放入列表中供用户选择
    180 
    181     while True:
    182         print("""33[95m ***使用说明:选择2和3时请务必按照字典的格式输入 选择4时以“,”隔开两个值 谢谢合作*** 33[0m""")
    183         choice = input("                              告诉我 你的选择  :")
    184         if choice == '5':
    185            exit("退出系统!")
    186 
    187         elif not choice.isdigit():continue #当用户输入字母时重新选择
    188         if int(choice) not in range(1,6): continue #当用户输入不在选择范围内时 重新选择
    189 
    190 
    191         data = input("输入你的数据:").strip()
    192         #当用户不选择第一个选项时,将输入的数据字典化
    193         if choice != '1':
    194             data = eval(data)
    195         choice_list[int(choice)-1](data)
    haproxy
  • 相关阅读:
    使用pod install 出现bad interpreter: No such file or directory
    简单易用且功能丰富的纯Swift下载框架
    Swift主题色顶级解决方案一
    如何基于WKWebView开发一个功能完善的资讯内容页
    关于iPhone X 的适配
    iOS11及Xcode9适配问题汇总
    优豆云
    Mac 网站屏蔽修改
    c语言
    iOS 12 前台通知shouldAlwaysAlertWhileAppIsForeground崩溃问题
  • 原文地址:https://www.cnblogs.com/lixiaoliuer/p/6182917.html
Copyright © 2011-2022 走看看