Python基础学习:文件读取

文件读取:

常用的文件读取方法:
file = open('thefile.txt') 读文件
file = open('thefile.txt', 'w') 写文件   每次通过w模式打开文件 以前文件内容会全部清空
content = file.read()  读取所有内容
content_part = file.read(100) 读取固定字节
content_oneline = file.readline() 读取一行内容
content_all = file.readlines()
file.close()
with open('/test.txt', 'r', encoding='UTF-8') as f:  # 打开新的文本
    text_new = f.read()  # 读取文本数据
print(text_new)

练习:

1. 请将python之禅zen.txt里面长度大于等于4的单词(不用处理标点符号,但要处理换行符),首尾各取2个字母组合成一个新的单词,并将这个单词添加到一
个列表里面,打印出来。

2. 编写一个简单的注册函数。要求用户输入用户名和密码,如果用户名为空或密码长度小于6位则提示用户错误信息后返回。如果用户输入正确,则提示用户注册成
功,并将该用户信息保存到本地文件中。要求保存时加入一个从0开始的整数id值,
每个用户的id值依次递增1。再次运行程序时,可以从已有的用户id值继续往下添加。

第一题:

with open('/zen.txt', 'r', encoding='UTF-8') as f:  # 打开新的文本
    text_new = f.read()  # 读取文本数据
poem_list = text_new.split('\n')
word_list = []
new_list = []
for poem_item in poem_list[::]:
    word_list.append(poem_item.split(' '))
for i in range(len(word_list) - 1):
    for j in range(len(word_list[i])):
        if len(word_list[i][j]) >= 4:
            new_list.append(word_list[i][j][0:2:] + word_list[i][j][-2:-1:] + word_list[i][j][-1::])
print(new_list)

第二题:

with open('/用户名密码信息.txt', 'r', encoding='UTF-8') as f:  # 打开新的文本
    text_old = f.read()  # 读取文本数据
with open('/用户名密码信息.txt', 'r', encoding='UTF-8') as f:  # 打开新的文本
    text_new = f.readlines()  # 读取文本数据

print(text_new[-1][0])
print(text_old)

user_name = input("请输入您的用户名:")
user_password = input("请输入您的密码:")
if user_name == '' or len(user_password) < 6:
    print("注册信息错误,请重新输入")
else:
    print("恭喜您,注册成功")
    with open('/用户名密码信息.txt', 'w', encoding='UTF-8') as f:  # 打开新的文本
        f.write(text_old)
        f.write('\n' + str(int(text_new[-1][0]) + 1) + ':' + ' ' + "username:" + user_name + ' ' + "userpassword:" + user_password)

 

附:

zen.txt文件内容如下:

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值