沉浸式过Python基础(4- 文件)

这篇博客介绍了Python中文件的基本操作,包括读取、写入和追加文件内容,以及使用with语句确保资源释放。此外,还展示了如何通过函数封装常见操作,并给出了文件备份和批量命名的示例。最后,涉及到了CSV文件的读取以及文件处理的最佳实践。
摘要由CSDN通过智能技术生成

文件
1.创建文件
2.打开 open()文件
3.处理(读read()写write())文件
4.关闭 close()文件

#==============================================================================
# #读文件
# f = open("text.text",mode="r",encoding="utf-8")
# f_content = f.read()
# print(f_content)
# f.close()
#==============================================================================

#==============================================================================
# #写(覆盖)文件
# f = open("text.text",mode="w",encoding="utf-8")
# w_content = f.write("write重写了这个文件")
# print(w_content)
# f.close()
#==============================================================================

#==============================================================================
# #追加文件内容
# f = open("text.text",mode="a",encoding="utf-8")
# a_content = f.write("write追加了这个内容")
# print(a_content)
# f.close()
#==============================================================================

#常规操作函数化
def Read_Write_File(filePath,mode_Type,Ope_Choice,size = None):
    '''
    filePath:   为文件路径+文件名 例如:D:\Python\Foundation Stage\stage1\text.text
    mode_Type:  r|w|a
    size:       读取内容的大小,默认为None,整型
    Ope_Choice: 读写操作read|write
    '''
    if Ope_Choice == "read":
        f = open("filePath","mode_Type","Ope_Choice",encoding="utf-8")
        print(f.read(size))
        f.close()
    elif Ope_Choice == "write":
        f = open("filePath","mode_Type","Ope_Choice",encoding="utf-8")
        print(f.write("write写了这个文件"))
        f.close()
    else:
        print("请填写操作类型(read|write)")

平时应用:文件读写操作后自动关闭释放资源(with as)

'''
file = open("/tmp/foo.txt")
data = file.read()
file.close()

#传统的try...finally语法
file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()
#with...as
with open("/tmp/foo.txt") as file:
    data = file.read()
'''

dict = [
      {"user1":123456},
      {"user2":123456}
      ]
with open("d.txt","w") as f2:
    for i in dict:
        for key,value in i.items():
            f2.write("{0}:{1}\n".format(key,value))


with open("d.txt","r") as f:
    #一次性读取readlines()
    content = f.readlines()
    i = 1
    for temp in content:
        print("%d:%s"%(i,temp))
        i+= 1
'''
1:user1:123456

2:user2:123456
'''        

import csv
with open("123.csv","r") as f3:
    list = []
    content = csv.reader(f3)
    for i in content:
        i.append(list)
print(list)

拓展:python 使用文件模块对文件进行备份
python 使用文件模块对文件进行批量命名操作(前缀后缀±)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不想想了

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

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

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

打赏作者

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

抵扣说明:

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

余额充值