Python中的文件读写

三大模式

r:只读模式

w:创建模式,若文件存在,则覆盖旧文件

a:追加模式,新数据写到文件末尾

python 复制代码
f=open("name_list",mode="w")

f.write("Lu Mingfei\n")
f.write("Lu Mingze\n")
f.write("Chen Wenwen\n")

f.close()

name_list.txt

python 复制代码
Lu Mingfei
Lu Mingze
Chen Wenwen

追加模式

python 复制代码
"""
追加模式
"""
f=open("name_list","a")

f.write("heheh\n")
f.write("jack")
# io.UnsupportedOperation: not readable,
print(f.read())
f.close()

name_list.txt

python 复制代码
Lu Mingfei
Lu Mingze
Chen Wenwen
heheh
jack

读文件

python 复制代码
"""
读文件
"""

f=open("name_list","r")
print(f.read())# 读出所有内容
"""
Lu Mingfei 
Lu Mingze  
Chen Wenwen
heheh      
jack 
"""

读文件二

superman.txt

python 复制代码
1. Ma 慕尼黑 50 123@qq.com
2. Qdl 爱丁堡 52 456@qq.com
3. Logistic 神奈川 49 790@qq.com
4. Luuly 洛杉矶 48 555@qq.com
5. Yeyedan 哥谭 54 321@qq.com
6. jerry 芝加哥 52 598@163.com
7. outama 西雅图 49 777@163.com

遍历文件

python 复制代码
"""
遍历文件
"""

"""
readlines():读所有行
[第一行,第二行,...,...]
['1. Ma 慕尼黑 50 123@qq.com\n', '2. Qdl 爱丁堡 52 456@qq.com\n', ...]
"""
f=open("superman.txt",encoding="utf-8")
print(f.readlines())


"""
1. Ma 慕尼黑 50 123@qq.com        
2. Qdl 爱丁堡 52 456@qq.com       
3. Logistic 神奈川 49 790@qq.com  
4. Luuly 洛杉矶 48 555@qq.com     
5. Yeyedan 哥谭 54 321@qq.com     
6. jerry 芝加哥 52 598@163.com    
7. outama 西雅图 49 777@163.com 
"""
f2=open("superman.txt",encoding="utf-8")
for line in f2:
    # end="" 表示 print 函数在打印完 line 之后不添加任何字符,也就是不换行。
    print(line,end="")
print("\n")



"""
多个列表,每一行是一个列表
['1.', 'MaQianxi', 'shenzhen', '173', '50', '13744234523']
['3.', 'LuoXinzu', 'beijing', '175', '49', '18623423421']
['4.', 'LuoNuohan', 'beijing', '170', '48', '18623423765']
['7.', 'YeZixuan', 'shanghai', '171', '49', '18042432324']
"""
f3=open("superman.txt",encoding="utf-8")
for line in f3:
    # 把当前读取的一行,转为list形式
    line=line.split()
    age=int(line[2])
    if age>=50 and age <=100:
        print(line)

写二进制文字

python 复制代码
#wb 写入二进制文件的模式
f=open("byteFile.txt","wb")

str="卡塞尔学院"
print(str.encode("utf-8"))
f.write(str.encode("utf-8"))

byteFile.txt

python 复制代码
卡塞尔学院
相关推荐
孟健3 分钟前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
躺平大鹅1 小时前
Java面向对象入门(类与对象,新手秒懂)
java
码路飞2 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
初次攀爬者2 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺2 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart3 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
曲幽4 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
NE_STOP4 小时前
MyBatis-mybatis入门与增删改查
java
孟陬8 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌8 小时前
一站式了解四种限流算法
java·后端·go