python文件操作

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值