# !/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