python简单文件操作

# 1.编写代码,输入一个文件路径,备份这个文件
import os
oldFileName = input("请输入你要备份的文件名:")
#判断是否是文件
if os.path.isfile(oldFileName):
    #找到分界线
    seekNum = oldFileName.rfind(".")
    #截取分界线以前的字符
    fileName = oldFileName[:seekNum]
    #截取分界线以后的字符
    fileFlag = oldFileName[seekNum:]
    print(fileName)
    #链接前后字符串
    newFileName = fileName + " - 副本" + fileFlag
    #读取老文件的内容
    oldFile = open(oldFileName,"rb")
    #写入新文件内容
    newFile = open(newFileName,"wb")
    #用变量存取读的内容
    content = oldFile.read()
    #讲读的内容写入新文件
    newFile.write(content)
    #关闭新老文件
    oldFile.close()
    newFile.close()
else:
    print("未找到该文件")
# 2.编写代码拷贝一个大文件到同目录下
old_File = open("bb.txt")
old_content = old_File.read()

new_file = open("vv.txt","w")
new_file.write(old_content)

new_file.close()
old_File.close()
# 3.读取一个文件,显示除了以井号(#)开头的行以外的所有行
# 打开文件
file003 = open("homework003.txt", "r", encoding="utf-8")
#方法一
# 读取文件内容
while True:
    # 读取一行内容
    content = file003.readline()
    # 如果是空的就退出
    if not content:
        break
    # 如果不是以#开头就输出
    if not content.startswith("#"):
        print(content, end="")
#方法二
# 读取文件内容
content = file003.read()
# 分割内容成为列表
content_list = content.splitlines()
# 遍历这个列表,如果元素不是# 开头就输出

for con in content_list:
    if not con.startswith("#"):
        print(con)

file003.close()
"""
4.制作一个"密码薄",其可以存储一个用户名(例如 qianfeng),
和一个密码(例如 123456),请编写程序完成这个“密码薄”的增删改查功能,
"""
#
# 打开文件
file004 = open("homework004.txt", "r+", encoding="utf-8")
# 读取文件内容
content = file004.read()
# 分割字符串,得到每一个人的信息是一行
content_list = content.splitlines()
# 输入查找的人名
name = input("请输入要修改的姓名:")

new_content_list = []

for con in content_list:
    # username01:123456
    if name == con.split(":")[0]:
        print("找到啦")
        password = input("请输入新的密码")
        new_content_list.append(name + ":" + password)
    else:
        new_content_list.append(con)
print(new_content_list)
file004.close()

# 写入新的内容
file004 = open("homework004.txt", "w+", encoding="utf-8")
for content in new_content_list:
    file004.write(content + "\n")
file004.close()

#5、歌词解析器

# 打开歌词文件
file = open("海阔天空.lrc", "r", encoding="utf-8")
# 读取歌词文件内容
str = file.read()
# 去除两端空格
str.strip()
# 创建字典,存储歌词和时间,key为时间,value为歌词
lrc_dict = {}
# 创建列表,获取分割后的歌词
lrc_list = str.splitlines()
# 遍历歌词
for lrc in lrc_list:
    # 取出方括号,分割歌词,得到时间和歌词
    lrc_line = lrc.replace("[", "]").strip().split("]")
    # 遍历分割后的歌词
    for j in range(len(lrc_line) - 1):
        # 把歌词放入字典
        if lrc_line[j]:
            lrc_dict[lrc_line[j]] = lrc_line[-1]
# 遍历字典
for key in sorted(set(lrc_dict.keys())):
    print(key, lrc_dict[key])
# 关闭文件
file.close()

猜你喜欢

转载自blog.csdn.net/qq_42336700/article/details/81394690