python第十六节(文件读写操作)

文件读写操作

练习

"""
1.获取当前工作文件夹,并且将内部文件已最后创建时间排序
--->获取最新创建的文件
"""
import os


def new_file(cur_dir):
    file_lis = os.listdir(cur_dir)  # 返回包含目录中文件名称的列表。
    # print(file_lis)
    time_lis = []
    for file in file_lis:
        # print(os.path.getmtime(file),file)  # 返回os.stat()报告的文件的最后修改时间。
        time_lis.append(os.path.getmtime(file))

    a = dict(sorted(zip(time_lis,file_lis)))  # 返回一个zip对象,该对象的._ next__()方法返回一个tuple where
            # 返回一个新列表,其中包含按升序排列的iterable中的所有项。
    print(a)


new_file(os.getcwd())  # 返回一个表示当前工作目录的unicode字符串

文件读写操作-只读模式

文件类型
.txt .doc .xls .ppt .rar .mpg .jpg .zip .pdf .avi .png .eps

只读模式

'''
1.打开文件
2.操作文件
3.关闭文件
r  # 只读 文件不存在则不可读(报错)
w
a
'''
f = open('test.txt', 'r', encoding='utf8')  # 打开文件并返回一个流。失败时提出OSError。
# print(f.readable())  # bool --> True

# print(f.read(5))  # 读取全部 \n 字符 换行符 汉字 只占1字节
# print(f.read(5))  # 读取全部 \n 字符 换行符 汉字 只占1字节

# print(f.readline(),end='')
# print(f.readline(),end='')
# print(f.tell())  # 汉字3个字节 字符一个字节 换行符 2个字节
# print(f.readline(),end='')
# print(f.tell())
# print(f.readline(9),end='')

# print(f.readlines()[1])  # 读取全部,[]  # 打印 ['666汗\n', '3434\n', '453434']
# print(f.readlines(6))

'''
第二行添加hello world
666汗
3434 hello world
453434
'''
# res = f.read()
# for i in res:
#     print(i)

res = f.readlines()
for i in range(len(res)):
    # print(res[i])
    if i == 1:
        print(res[i].strip(), 'hello world')
        # strip()返回字符串的一个副本,并删除开头和结尾的空白。
    else:
        print(res[i],end='')
'''
read()
readline()
readlines()
'''

w模式与a模式

'''
模式与方法要匹配
w --> 文件不存在 创建文件
'''
# f = open('text1.txt', 'w')
# print(f.writable())  # bool

# f.write('hello amy')  # 覆盖掉

# f.writelines(['hello world\n','hello world'])

'''
a 文件不存在时,创建文件
'''
f = open('text2.txt','a')
f.write('hello amy \n')  # a 是追加

r加与w加

'''
r+  可读可写 以r为主导,并且拥有w,a权限
w+
a+
'''
# f = open('test3.txt','r+')
# f.write('hello world')

f = open('test4.txt','w+')
# f.write('hello world')
# print(f.readable())  # True
print(f.read())

上下文管理器

'''
图片
音频
二进制
'''
# b = b'hello world'
# # print(type(b))  # byte
# f = open('test5.txt','wb')
# f.write(b)  # w对文本流操作 只能写入 str

'''
json.dumps()-->语句
json.dump()-->文件
'''
import json
# data = {"name":"amy"}
# res = json.dumps(data)
# print(res)
# print(type(res))

# print(type(data))  # dict
# f = open('test6.json','w')  # dict-->'{"name":"amy"}'
# json.dump(data,f)

# f = open('test6.json','r')
# # print(type(f.read()))  # '{"data":{"name":{}}}'
# d_data = json.load(f)
# print(d_data['name'])
# print(type(d_data))

'''
f.close()-->关闭文件
写入 是在f.write()写入?还是程序执行完毕才写入?
'''
# import time
# f = open('test6.txt','w')
# f.write("hello world")  # 程序执行完毕才写入
# time.sleep(5)
# f.close()

try:
    f = open('test6.txt','w')
    f.read()
except Exception as e:
    print(e)
finally:
    if f:
        f.close()

上下文管理器

'''
with自动调用__enter__(),将方法的返回值赋值给as后的变量-->f = open()
with后面的代码块全部执行完毕之后,将调用前面返回对象的__exit__() -->f.close

上下文管理器
with open() as f:
    pass
'''
with open('test7.txt','w') as f:
    f.write('hello world')

'''
与open()使用没有太大的区别
唯一的区别是,with open() 自动关闭
open()需要自己f.close()
'''

制作文件备份

'''
制作文件备份
1.用户输入需要备份的文件名
2.读取文件内容
3.将读取出来的文件内容 写入另一个文件
'''
filename =input("请输入需要备份的文件名:")
f = open(filename,'r')
content = f.read()

# 副本名称-->test1.txt -->test1副本.txt
position = filename.rfind('.')  # 从右边开始 获取.的索引
new_file_name = filename[:position] + '副本' +filename[position:]
f1 = open(new_file_name,'w')
f1.write(content)

f.close()
f1.close()
发布了30 篇原创文章 · 获赞 0 · 访问量 685

猜你喜欢

转载自blog.csdn.net/luobofengl/article/details/104307217