文件操作

#文件的 打开方式 与功能

#绝对路径 是根目录下的
#相对路径 是同一个文件夹下的 文件就是相对路径

#f = open("E:\lx.txt",encoding = "gbk",mode = "r")
# open 他是windows系统命令, 注意路径 和 文件的 编码方式
# mmode = "r" 可以不写 , 不写 默认为只读
# r : 只读 r+ 可读可写,先读后写 rb 以字节的模式读文件
#f 变量:f f_obj, obj, file_hl, file_hanlder 文件句柄
# 通过对文件句柄的操作,来得到你想要的东西.
# content = f.read()
# print(content)
# f.close() #将你的文件句柄,或者是动作关闭,节省内存

#rb b表示为bytes 字节 一般用于非文字类型的文件;图片,视频
# 文件的下载和上传的功能用 b M模式
# rb 为二进制模式 不需要编码参数
# f = open("lianxi","rb")
# content = f.read()
# print(content)
# f.close()

# r 读有五种模式
# 1. f.read()全部读出来 因为打开文件是从内存中进行的 如果文件太大
#的话 电脑会蓝屏

#2 f.readline() 按行读 麻烦,没效率
# f = open("lianxi",encoding="utf-8")
# line = f.readline()
# print(line)
# line = f.readline()
# print(line)
# f.close()

# 3 .f.readlines() 每一行作为一个元素, 放在列表中
# f = open("lianxi",encoding="utf-8")
# line = f.readlines()
# print(line)
# f.close()

# 4 . for in 循环去读文件 最好的方式。
# f = open("lianxi",encoding="utf-8")
# for i in f:
# print(i)
# f.close()

# 5 . f.read(n) n 表示自己的个数
# f = open("lianxi",encoding="utf-8")
# content = f.read(12) # rb模式 n 是按照字节获取
# print(content)
#f.close()

# f = open("lianxi",mode = "rb")
# content = f.read(3) # rb 模式 是按照字节读取
# print(content)
# f.close()

# bytes 转化为 str
# s = b"\xe4\xb8\xb0".decode("utf-8")
# print(s)

# 只写w wb w+可读可写,先读后写 如果没有文件,则创建文件写内容,
# 如果有文件则将原文件 内容 全部删除,再写。
# f = open("lianxi2","w",encoding="utf-8")
# f.write("alex")
# f.close()
# f = open("lianxi2","w",encoding="utf-8")
# f.write("alex333")
# f.close()

#追加 a ab 在最后追加 a+可读可写,先读后写
# f = open("lianxi2","a",encoding="utf_8")
# f.write("wusir是xxx")
# f.close()

# seek 移动广标 按照字节跳整位置
# f = open("lianxi","w+",encoding="utf-8")
# f.write("333333")
# f.seek(0) # 移动广标 按照字节调整
# print(f.read())
# f.close()

# truncate 截断
# f = open("lianxi","a",encoding="utf-8")
# f.truncate(3) # 截断按照字节去截 截取前面的内容
# f.close()

# python 内部 的 打开文件的 简单方法:
# with open("lianxi","r",encoding="utf-8")as f1,\
# open("lianxi2","r",encoding="utf-8")as f2:
# print(f1.read())
# print(f2.read())

#python 内部 改动文件 清除版
import os
#1,创建一个新文件。
# with open("lainxi",encoding="utf-8")as f1,\
# open("lianxi2","w",encoding="utf-8")as f2:
# #2.读取元文件
# old_content = f1.read()
# new_content = old_content.replace("alex","sb")
# f2.write(new_content)
# #3.将原文件的内容通过你想要额方式进行更改,并写入新文件。
# #4.将原文件删除。
# os.remove("lainxi")
# #5,将新文件重命名原文件名。
# os.rename("lianxi2","lainxi")


#简便版
# import os
# #1,创建一个新文件。
# with open("lainxi",encoding="utf-8")as f1,\
# open("lianxi2","w",encoding="utf-8")as f2:
# #2.读取元文件
# for i in f1:
# i = i.replace("alex","sb")
# f2.write(i)
# #3.将原文件的内容通过你想要额方式进行更改,并写入新文件。
# #4.将原文件删除。
# os.remove("lainxi") # 路径
# #5,将新文件重命名原文件名。
# os.rename("lianxi2","lainxi")

#str 转化为 bytes 类型

#"alex" ----> "alex".encode("utf-8") 编码
# bytes -----》str
#b"alex" ---->b"alex".decode("utf-8") 解码
posted @ 2018-03-24 13:49  xuerh  阅读(159)  评论(0)    收藏  举报