Python文件基本操作-1

一、基本操作流程

(1)打开文件:f=open(filename)
(2)读操作:f.read(读全部)或f.readline(读一行)
(3)写操作:f.write()
(4)保存并关闭:f.close()
注意:
f.write()写入新内容需要结尾使用f.close(),如果只读不需要f.close()。
f.read(10) # 读10个字符

二、文件打开模式(文本模式)

(1)f=open(filename,“r”) #只读模式打开,不可修改
(2)f=open(filename,“w”) #创建模式,若文件存在,则覆盖旧文件
(3)f=open(filename,“a”) #追加模式,新数据会写道文件末尾
如果filename是中文,则需要添加 encoding=“utf-8”,如下:
f=open("个人信息,“r”,encoding=“utf-8”)

### 追加模式
f=open('D:/Doc Operation/hello-txt.txt',"a")
f.write("\n")  # 先换行
f.write("Author is Xia")
f.close()

三、文本光标位置

当文件读或写一个字符,光标也会往后移1位。
f.seek() # 把操作文件的光标移到指定位置
f.tell() # 返回光标位置

f =open("seek-write.txt","w")
f.write("hello1\n")
f.write("hello2\n")
f.write("hello3\n")
f.seek(20)   # seek把操作文件的光标移到指定位置
f.write("----")   # 从20处开始写内容
print("返回光标位置",f.tell())   # tell()返回光标位置
f.close()
##输出结果:
hello1
hello2
hell----

四、循环文件

f=open(filename)
for line in f:
例:个人信息.txt内容如下,要求:
(1)返回身高大于170cm,体重小于50kg
(2)写入字典中
在这里插入图片描述

f=open("D:/Doc Operation/个人信息.txt","r",encoding="utf-8")
#在读取以中文命名的文件时,需要添加 encoding="utf-8"
information={}
for line in f:
    line=line.split() # 按照空格分割
    height=int(line[3])
    weight=int(line[4])
    if height>=170 and weight<=50:
        print(line)
    information[line[1]]=line   # 写入字典中
print(information["叶梓萱"])

五、二进制操模式

打开模式:“rb”、“wb”、“ab”,常用于读取图片、.db等文件

f=open("D:/Doc Operation/测绘人生.jpg","rb")
print(f.read())

六、文件其他功能

(1)f.mode # 返回文件打开模式
(2)f.name # 返回文件名
(3)f.flush() # 把文件从内存buffer里强制刷新到硬盘
(4)f.readline() # 只读一行
(5)f.seek(10) # 把操作文件的光标移动到指定位置
(6)f.tell() # 返回当前光标位置
(7)f.truncate() # 按指定长度截断文件,常和f.seek(0)一同使用
(8)f.readable() # 判断是否可读,若可读返回True
(9)f.writable() # 判断是否可写,若可读返回True

## 清空文件 ,用于读取文件后重新写入新内容##
f.seek(0)  # 光标移动到0处
f.truncate()   #截断文件

七、文件打开模式(混合模式)

“r+”:即能读又能写,但都是写在文件最后,跟追加一样。

### 替换文本内容  ###
f=open("D:/Doc Operation/个人信息.txt","r+",encoding="utf-8")
# 1. 加载到内存
data=f.read()
new_data=data.replace("夏雪","夏")  # 将本文中“夏雪”替换称“夏”
# 2. 清空文件##
f.seek(0)  # 光标移动到0处
f.truncate()   #截断文件
# 3. 把新内容写回硬盘
f.write(new_data)
# 4.关闭并保存
f.close()

八、文件的修改

(1)全区文本检索替换
要求:在Terminal(终端)写入 python file_replace.py 夏 Shelyer D:/Doc Operation/个人信息.txt 后实现内容替换。
在这里插入图片描述

import sys
print(sys.argv)   # 实现命令行转成列表
old_str=sys.argv[1]
new_str=sys.argv[2]
filename=sys.argv[3]
# 1.打开文本
f=open(filename,"r+",encoding="utf-8")
data=f.read()
# 2. count and replace
old_str_count=data.count(old_str)  #统计old_str有几个
new_data=data.replace(old_str,new_str)  #将old_str替换为new_str
# 3. chear old filename
f.seek(0)  # 将光标移动到0
f.truncate()  # 截断文件
# 4. save new data into file
f.write(new_data)
print(f"成功替换字符'{old_str}' to '{new_str}',共{old_str_count}处...")
f.close()

(2)用户登录认证程序
重点知识点:
双重循环及while True:
重新写入

# -*- coding: utf-8 -*-

# 1.确定在文件里存储的账号信息的结构
# user,password,1/0   # 1表示可用账户,0表示被锁定账户
# xia,123,1
# dai,123,1
# wang.123,1

# 2.把账号数据读到内存,使用字典存放
accounts={}
f=open("user information.txt","r")
for line in f:
    line=line.strip().split(",")   # strip()去除空格、换行符等
    accounts[line[0]]=line

# 3. 整个loop,要求用户输入账号信息,去判断
while True:     # 当条件为真时,执行以下操作
    user=input("用户名:").strip()
    if user not in accounts:  # 用户未注册
        print("该用户未注册") 
        continue
    elif accounts[user][2]=="0" :    #当第3列为0时,该账号被锁定
        print("账号已锁定,请联系管理员")
        continue
    count=0
    while count<3: 
        passwd=input("密码:").strip()
        # 账号正确,判断密码对不对
        if passwd==accounts[user][1]:
            print(f"欢迎{user},登录成功")
            print("Bye")           
            break
        else:
            print("Wrong Password")
        count+=1
        
    # # 4. 锁定账户,写入原本文中
    if count==3:
        print(f'输错了{count}此密码,需要锁定账号{user}')
        # 4.1 先改在内存中的dict账号信息,用户状态
        # 4.2 把dict里的数据转成原有格式,并存回文件
        accounts[user][2]="0"
        f2=open("user information.txt","w")
        for i in accounts:  #循环字典
            val=accounts[i]
            wt=",".join(val)+"\n"
            f2.write(wt)
        f2.close()
        print("bye")           
        break
        
#  ''.join(list)   将列表中的元素以指定的字符连接生成一个新的字符串
# 其中,引号中是字符之间的分割符,如“,”,“;”,“\t”等等      
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shelyer1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值