目录
读写文件
现有账单文件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
记得将用户文件放在默认路径里