# !/use/bin/env python
# -*-conding:utf-8-*-
# author:shanshan
"""
6,有名为poetry.txt的文件,其内容如下,请删除第三行;
昔人已乘黄鹤去,此地空余黄鹤楼。
黄鹤一去不复返,白云千载空悠悠。
晴川历历汉阳树,芳草萋萋鹦鹉洲。
日暮乡关何处是?烟波江上使人愁。
"""
def delete_third_line():
    """
    第一种方式,将文件内容读取到内存中,内存中是可以对内容进行增删改查的。但是硬盘不可以
    :return:
    """
    with open('poetry.txt', 'r', encoding='utf-8')as f:
        list_file = f.readlines()
        list_file.pop(2)  # 这是一个列表
        str_file = ''.join(list_file)  # 转为字符串
    with open('poetry.txt', 'w', encoding='utf-8')as f:
        f.write(str_file)  # 写入删除后的字符串
# delete_third_line()
def delete_third_line_2():
    """
    第二种方式,边读边写的方式,每次只占用一行内容的内存,但缺点就是占用硬盘。你想啊打开了两个文件呢
    :return:
    """
    import os
    with open('poetry.txt', 'r', encoding='utf-8')as f:
        for i in f:
            if '晴川历历汉阳树,芳草萋萋鹦鹉洲' in i:  # 如果  存在这句则跳过
                continue
            else:  # 否则写入副本
                with open('poetry.txt(副本)', 'a', encoding='utf-8')as fd:
                    fd.write(i)
    os.replace('poetry.txt(副本)', 'poetry.txt')  # 将poetry.txt副本进行重命名为:poetry.txt,并删除之前已有的poetry.txt文件
    # 为啥不用os.renames()因为他只有重命名
# delete_third_line_2()
"""
4,有名为username.txt的文件,其内容格式如下,写一个程序,
判断该文件中是否存在”alex”, 如果没有,则将字符串”alex”添加到该文件末尾,否则提示用户该用户已存在;
   pizza
   alex
   egon
"""
def if_alex_file(name):
    with open('username.txt', 'r+', encoding='utf-8') as f:
        if name in f.read():  # 注意不要用文件对象f,<class '_io.TextIOWrapper'>
            print('{}用户已存在'.format(name))
        else:
            with open('username.txt', 'a', encoding='utf-8') as fd:
                fd.write('\n' + name)
# if_alex_file('alexb')
"""
5,有名为user_info.txt的文件,其内容格式如下,写一个程序,删除id为100003的行;
   pizza,100001
   alex, 100002
   egon, 100003
"""
import os
def delete_100003():
    with open('user_info.txt', 'r', encoding='utf-8')as f:
        for i in f:
            if '100003' in i:
                continue
            else:
                with open('user_info.txt(副本)', 'a', encoding='utf-8')as fd:
                    fd.write(i)
    os.replace('user_info.txt(副本)', 'user_info.txt')
# delete_100003()
"""
6,有名为user_info.txt的文件,其内容格式如下,写一个程序,将id为100002的用户名修改为alex li;