Python基础(文件与目录管理)

目录

读写文件

修改目录

 认证模拟程序


读写文件

 现有账单文件bill.txt,记录了消费收入的具体情况,读取该文件,并将文件中的“正式”数据写入到备份文件bill.txt.bak中。

# 读取写入
# 打开文件
f1 = open(r"你的路径\test\bill.txt", 'r', encoding='UTF-8')
f2 = open(r"你的路径\test\bill(bak).txt", 'w')

# 读取文件
for line in f1:
    line = line.strip()
    words = line.split(',')
    if words[-1] == '测试':    # 去掉带测试的
        continue
    # 或用切片(去split):if line[-2:] == '测试':
    f2.write(line)
    f2.write('\n')

# 关闭文件
f1.close()
f2.close()

# 法二 自动关闭
f3 = open(r"C:\Users\dell\Desktop\test\bill(bak)1.txt", 'w')
with open(r'C:\Users\dell\Desktop\test\bill.txt', 'r', encoding='UTF-8') as f1:
    for line in f1:
        if '正式' in line:
            f3.write(line)

修改目录

使用python批量修改文件夹中的文件名,去掉文件名中的“.bak”。 

import os
dirlist = os.listdir(r'你的路径\test\test')  # 获取文件列表名
print(dirlist)
os.chdir(r'你的路径\test\test')  # 更改默认目录,Python解释器会找默认路径下的
for oldname in dirlist:
    newname = oldname[:-8] + oldname[-4:]
    os.rename(oldname, newname)
    

如不更改默认路径,会:

结果:

 认证模拟程序

创建一个文件user.txt,文件上输入多行用户名及对应的密码(用户名和密码用冒号分开)。编写一个认证的模拟程序,让客户输入用户名和密码,进行用户名和密码核对。如果输入正确,则显示认证成功,如果不正确,提示用户名或密码错误。 

def authenticate(username, password):

    # 读取用户文件
    with open("user.txt", 'r') as file:
        lines = file.readlines()

    # 检查输入的用户名和密码是否匹配
    for line in lines:
        stored_username, stored_password = line.strip().split(':')
        if username == stored_username and password == stored_password:
            return True
    return False

# main
if __name__ == '__main__':
    # 获取用户输入
    input_username = input("请输入用户名:")
    input_password = input("请输入密码:")

    # 进行认证
    if authenticate(input_username, input_password):
        print('认证成功!')
    else:
        print('用户名或密码错误!')

写个用户文件:

user123:pass123
john_doe:securepass
coding_master:python123
dog_lover:ilovemydog
happy_user:happy123

 记得将用户文件放在默认路径里

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值