第30天 | 32天学会python, 文件操作

python里使用open内置函数打开并操作一个文件
# open参数介绍:
# 1.file用来指定打开的文件(不是文件名,而是文件的路径)
# 2.mode打开文件时的模式,默认是r表示只读
# 3.encoding打开文件时的编码方式,windows系统下默认是gbk
file = open('xxx.txt',encoding='utf8')  # open函数会有一个返回值,打开文件的内容
print(file.read())  # 上面open参数不写encodings='utf8'的话,这里读会报错
# xxx.txt写入时使用的是utf8编码格式;在windows操作系统里,打开文件,默认使用gbk编码格式打开

file.close() # 操作完成文件后,要关闭文件,良好的习惯 

文件的路径

# 路径分为两种:
# 1).绝对路径:从电脑盘符开始的路径
# 为什么直接粘贴文件路径不行呢?windows系统里,文件夹之间使用\分割,但在Python的字符串里 \ 表示转义字符
# 1.使用双反斜杠表示的就是一个反斜杠
file = open('D:\\python编程\\学习项目\\文件操作\\xxx.txt',encoding='utf8')
print(file.read())   # 今天是个好天气!!!
file.close()  # 关闭文件
# 2.可以使用 r 解决这个问题
甲 = open(r'D:\python编程\学习项目\文件操作\xxx.txt',encoding='utf8')
print(甲.read())  # 今天是个好天气!!!
甲.close()  # 关闭文件
# 3.在非windows系统里,使用 / 分割文件夹,同样在windows系统也能识别,推荐这个方法在哪个平台都能使用
乙 = open('D:/python编程/学习项目/文件操作/xxx.txt',encoding='utf8')
print(乙.read())  # 今天是个好天气!!!
乙.close()

# 2).相对路径:当前文件所在的文件夹开始的路径
丙 = open('demo/sss.txt',encoding='utf8')  # 程序运行的路径
print(丙.read())  # 嘻嘻嘻,呜呜呜,嘿嘿嘿
丙.close()
丁 = open('../ppp.txt') # 程序运行的路径的上一层
print(丁.read())  # 呼呼呼,啦啦啦,顿顿顿
丁.close()

文件的打开方式

# mode 值的是文件的打开方式
# 1.r :只读模式,默认的,打开文件后,只能读取,不能写入;如果文件不存在会报错
甲 = open('xxx.txt','r',encoding='utf8')
print(甲.read())
# 甲.write('hello') # 会报错,只有可读权限
甲.close()

# 2.w :写入模式,打开文件以后,只能写入,不能读取
乙 = open('xxx.txt','w',encoding='utf8')
# print(乙.read())  # 会报错没有可读权限
乙.write('你好')  # 写入的操作
乙.close()

# 3.b :以二进制的形式打开文件&写入文件
丙 = open('xxx.txt','rb')
print(丙.read())  # b'\xe4\xbd\xa0\xe5\xa5\xbd'
丙.close()
丁 = open('xxx.txt','wb')
丁.write('大家好才是真的好'.encode('utf8'))  # 写入大家好才是真的好
丁.close()
# a:追加模式,会在最后追加内容.如果文件不存在,会创建文件,如果文件存在会追加
# r+和w+是可读写,他们的区别:r+写入不会覆盖旧内容,如果文件不存在会报错,w+写入覆盖旧内容,如果文件不存在会创建文件
戊 = open('xxx.txt','w+',encoding='utf8')
戊.seek(0,0)  # 写入之后,文件指针到最后,需要调用seek将文件指针重置到首部
戊.write('你好吗')
print(戊.read())

文件拷贝

import os

file_name = input('请输入一个文件路径:')  # sss.txt -->sss.bak.txt
if os.path.isfile(file_name):
    old_file = open(file_name, 'rb')  # 打开旧文件

    # names = file_name.rpartition('.')  # ('sss', '.', 'txt')
    names = os.path.splitext(file_name)  # ('sss', '.txt')
    print(names)

    new_file_name = names[0]+'.bak'+names[1]
    new_file = open(new_file_name, 'wb')  # 打开一个新文件用于写入
    while True:
        二进制 = old_file.read(1024)  # 读取出来的内容是二进制
        new_file.write(二进制)  # 把旧文件的数据读取出来写入到新的文件
        if not 二进制:
            break

    old_file.close()
    new_file.close()
else:
    print('您输入的文件不存在')

文件读取方式

# Python里使用 open 内置函数用来打开一个文件
# file:文件的路径.相对路径和绝对路径
# mode:打开文件的模式.r:只读 w:写入 b:二进制 t:文件形式打开
# mode 默认使用rt
# enccoding:用来指定文件的编码方式.windows系统里默认是gbk(gb2312)

# file = open('xxx.txt') # 报错,默认是以rt打开,如果文件不存在,会报错
file = open('sss.txt','w',encoding='utf8')  # 创建一个新的文件
file.write('你好')

file = open('sss.txt', encoding='utf8')
# 1.# 将所有的数据都读取出来
print(file.read())  
丙 = file.read(10)  # 参数指的是读取的长度
print(丙)
# 2.readline只读取一行数据
while True:
    甲 = file.readline()
    print(甲)
    if 甲 == '':
        break
# 3.readlines 读取所有行数据,保存到一个列表里
乙 = file.readlines()
print(乙)  # ['你好\n', '早上好\n', '下午好\n', '晚上好\n', '哈哈哈\n', '嘻嘻嘻\n', '嘤嘤嘤\n']

# 全读的话压力很大
丙 = open(r'D:/stable diffusion/模型训练工作台/视频集/风景/111.mp4','rb')
print(丙.read())
file.close()
# 指定大小读:
while True:
    丁 = 丙.read(1024)
    if not 丁:
        break
    print(丁)
# 优化:没有绝对的优化,除非提升硬件
# 软件层面优化: 时间 / 空间


CSV文件的读写

import csv

# 1.写入csv文件
file = open('demo.csv','w',encoding='utf8',newline='')  # 先打开一个文件
甲 = csv.writer(file)  # 编写的对象
# writerow写单行
甲.writerow(['name','age','score','city'])
甲.writerow(['zhangsan','19','90','襄阳'])
甲.writerow(['lisi','19','90','纽约'])

# writerows写多行,用编写对象写入内容到打开的文件
甲.writerows([
    ['name','age','score','city'],
    ['zhangsan','19','90','襄阳'],
    ['lisi','19','90','纽约']
])
file.close()

# 2.读取csv文件
file2 = open('info.csv','r',encoding='utf8',newline='')  # 先打开一个文件
乙 = csv.reader(file2)  # 读取文件内容
print(乙)  # <_csv.reader object at 0x0000000002432E20> 返回的是一个_csv.reader对象:可迭代对象
for 丙 in 乙:
    print(丙)
file2.close()



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值