1.读取文件:使用read方法读取文件:
ft=open('xxx.txt','r')
content=ft.read(6)
print(content)
print("**"30)
content=ft.read()
print(content)
ft.close()
使用readline方法一行一行读取数据:
with open("xxx.txt","rt")as ft:
content=ft.readline()
while content!="":
print(content.end='')
print=ft.readline()
使用readline方法读取文件:
ft=open("xxx.txt","rt")
content_lidt=ft.readlines()
for line in content_list:
print(line,end="")
ft.close
2.使用write方法写入文件:
ft=open("aaa.txt","w")
ft.write("love peace")
ft.close
使用writelines方法写入文件:
ft=open("wf.txt","wt")
lines=["love","peace"]
ft.writelines(lines)
ft.close()
3.使用tell()方法来获取文件当前的读写位置:
f=open("love.txt","r")
str=f.read(4)
print("读取的数据是:",str)
position=f.tell()
print("当前文件位置:",position)
例题如下:示例,从一份班级花名册中,随机抽取三个中奖的学生。算法思路如下:1.用readline()读取花名册文件内容到姓名列表.2 .random库choice方法随机在列表中抽第一个奖.3.random库choice方法随机在列表中抽第一个奖.4.random库choice方法随机在列表中抽第一个奖.5.倒计时三秒后,输出中奖学生名单.代码如下:
import random
import time
f=open('花名册.txt',mode='r',encodiing='utf-8')
list_name=f.readlines()
lucky_stu1=random.choice(list_name)
lucky_stu2=random.choice(list_name)
lucky_stu3=random.choice(list_name)
print("选择学生倒计时开始:")
for i in range(3):
print(3-i)
time.sleep(1)
f.close()
print(lucky_stu1,lucky_stu2,lucky_stu3)