>>> fp=open("aa.txt","w+")
>>> fp.write("好好学习\n")
5
>>> fp.write("天天向上\n")
5
>>> fp.seek(0,0)
0
>>> fp.readline()
'好好学习\n'
>>> fp.readline()
'天天向上\n'
>>> fp.readline()
''
>>> fp.close()
>>> fp=open("aa.txt","r+")
>>> fp.readline()
'好好学习\n'
>>> fp.readline()
'天天向上\n'
>>> fp.seek(0,0)
0
>>> fp.write("hello world\n")
12
>>> fp.seek(0,0)
0
>>> fp.readline()
'hello world\n'
>>> fp.readline()
'向上\n'
>>> fp.readline()
''
>>> fp.close()
>>> fp=open("aa.txt","a+")
>>> fp.readline()
''
>>> fp.seek(0,0)
0
>>> fp.readline()
'hello world\n'
>>> fp.seek(0,0)
0
>>> fp.write("加油!") #a+模式下,永远写在最后面
3
>>> fp.seek(0,0)
0
>>> fp.read()
'hello world\n向上\n加油!'
>>> fp.close()
>>> fp=open("aa.txt","r+")
>>> fp.read(10)
'hello worl'
>>> fp.readline(2)
'd\n'
>>> fp.readline(2)
'向上'
>>> fp.readline(2)
'\n'
>>> fp.readline(2)
'加油'
>>> fp.close()
句柄泄露
>>> fp1=open("aa.txt","r+")
>>> fp2=open("aa.txt","r+")
>>> fp1.readline()
'hello world\n'
>>> fp2.readline()
'hello world\n'
>>> with open("aa.txt") as fp:
... print(fp.read())
...
hello world
向上
加油!
#with的实现原理
class Sample:
def __enter__(self):#准备的时候干什么事儿,返回的结果
#存在as 后面的变量里面
print("In __enter__()")
return "Foo"
#with主体代码结束后需要做的事情
def __exit__(self, type, value, trace):
print("In __exit__()")
def get_sample():
return Sample()#返回了类的实例
#with的实现机制:上下文管理机制
with get_sample() as sample:
print("sample:", sample)
"""
__enter__方法:定义了执行with下面代码之前,需要做的事情通常是资源准备。
__exit__方法:定义了执行with下面代码之后,需要做的事情通常是资源释放和清理。
这两个方法关联到了with的代码块,以此实现了上下文管理机制。
as sample中的sample值来自于__enter__方法的返回值。
"""
"""
结果:
In __enter__()
sample: Foo
In __exit__()
"""
>>> pic1=open("1.jpg","rb")
>>> pic2=open("new_1.jpg","wb")
>>> content=pic1.read()
>>> pic2.write(content)
28436
>>> pic1.close()
>>> pic2.close()
>>> fp=open("aa.txt","r")
>>> print(fp.closed) #文件是否被关闭
False
>>> print(fp.mode) #文件以什么模式打开
r
>>> print(fp.name) #文件名称
aa.txt
>>> fp.close()
>>> print(fp.closed)
True
>>> fp=open("aa.txt","w")
>>> fp.writelines(["好好学习\n","天天向上\n"]) #写入多行
>>> fp.close()
fp.tell():返回游标所在位置
fp.seek():移动游标位置
fp.truncate():截取文件,括号输入截取字节数量。默认是裁到当前文件操作标记的位置。如果要裁的内容比文件还大,则可能不改变文件,或补0或者随机加入内容。
7.linecache模块:不常用,用时候百度吧!
8.序列化:Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为持久地储存对象(序列化)。
>>> fp=open("aa.txt","wb")
>>> a=100
>>> b=[1,2,3]
>>> pickle.dump(a,fp)
>>> pickle.dump(b,fp)
>>> fp.close()
>>> ^Z
#再次进入cmd
>>> import pickle
>>> fp=open("aa.txt","rb")
>>> a=pickle.load(fp)
>>> a
100
>>> b=pickle.load(fp)
>>> b
[1, 2, 3]
>>> fp.close()
#创建五级目录,每级有同名文件,文件内容同文件名
import os
os.chdir("d:\\test")
for i in range(1,6):
os_flag="test"+str(i)
os.mkdir(os_flag)
os.chdir(os_flag)
fp=open(os_flag+".txt","w")
fp.write(os_flag)
fp.close()
print("执行完毕")
>>> os.getcwd()
'd:\\test\\test1'
>>> os.chdir(os.pardir)
>>> os.getcwd()
'd:\\test'
>>> os.chdir("..")
>>> os.getcwd()
'd:\\'
#encoding=utf-8
import os
#root表示当前被访问的目录名称
#dirs表示当前目录中所有的子目录名称(元祖)
#dirs表示当前目录中所有的文件名称(元祖)
#最外层for实现了,每一个目录的遍历
for root, dirs, files in os.walk("d:\\test",topdown=False) :
print(u"当前目录:",root) #打印目录绝对路径
for name in files :#内层for实现了,遍历某一个目录中所有的文件名称
print(u'文件名:',os.path.join(root,name) )#打印文件绝对路径
for name in dirs :#实现遍历某一个目录中的所有子目录名称
print(u'目录名:',name) #打印目录绝对路径
print("*"*20)
>>> os.path.abspath("aa.txt")
'D:\\test\\aa.txt'
>>> os.path.abspath("aaaaa.txt")
'D:\\test\\aaaaa.txt'
>>> os.path.split('D:\\test\\aaaaa.txt')
('D:\\test', 'aaaaa.txt')
>>> os.path.dirname('D:\\test\\aaaaa.txt')
'D:\\test'
>>> os.path.basename('D:\\test\\aaaaa.txt')
'aaaaa.txt'
>>> os.path.exists('D:\\test\\aaaaa.txt')
False
>>> os.path.exists('D:\\test\\aa.txt')
True
>>> os.path.isabs("D:\\test\\aa.txt")
True
>>> os.path.isabs("aa.txt")
False
>>> os.path.isfile("aa.txt")
True
>>> os.path.isfile("D:\\test\\aa.txt")
True
>>> os.path.isfile("D:\\test")
False
>>> os.path.isdir("d:\\")
True
>>> os.path.isdir("d:\\test\\aa.txt")
False
>>> os.getcwd()
'D:\\test'
>>> os.remove("aa.txt")
>>> os.path.getsize("1.jpg")
28436
>>> os.path.join("d:\\test","a.txt")
'd:\\test\\a.txt'
>>> os.path.splitext("d:\\test\\a.txt")
('d:\\test\\a', '.txt')
>>> os.path.splitdrive("d:\\test\\a.txt")
('d:', '\\test\\a.txt')
>>> os.path.getatime("d:\\test\\1.jpg")
1593671456.6549156
>>> lastTime=os.path.getatime("d:\\test\\1.jpg")
>>> import time
>>> time.localtime(lastTime)
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=2, tm_hour=14, tm_min=30, tm_sec=56, tm
_wday=3, tm_yday=184, tm_isdst=0)
#判断某个目录下有多少个文件和目录,如果有txt请删除
import os
os.chdir("d:\\test")
l=os.listdir("d:\\test")
print(l)
file_num=0
dir_num=0
for i in l:
if os.path.isfile(i):
file_num+=1
if ".txt" in i:
os.remove(i)
pass
else:
dir_num+=1
l=os.listdir("d:\\test")
print(l)
print("目录数:",dir_num)
print("文件数:",file_num)
print("执行完毕")
本文地址:https://blog.csdn.net/Teeeeesting/article/details/107159058
如对本文有疑问, 点击进行留言回复!!
ubuntu环境下利用Wand将pdf转jpg, python代码
荐 Python可视化matplotlib13-iris鸢尾花数据集|histogram直方图
网友评论