本篇文章主要介绍了"python爬虫 python学习 文件操作",主要涉及到python爬虫方面的内容,对于Pythonjrs看球网直播吧_低调看直播体育app软件下载_低调看体育直播感兴趣的同学可以参考一下:
一、python打开文件#=====================python 文件打开方式 open()=====================# ope...
一、python打开文件
#=====================python 文件打开方式 open()=====================# open(fileName,type) type="r" 以只读方式打开文件 ,该文件必须存在file_r=open("E:\\python\\hello.txt","r");
# open(fileName,type) type="w"#1、以只写方式打开文件 ,该文件如果不存在就创建文件#2、如果该文件存在并且有内容,则会清空内容file_w=open("E:\\python\\hello_w.txt","w");
# open(fileName,type) type="a" 以追加的方式打开文件file_a=open("E:\\python\\hello_w.txt","a");
# open(fileName,type) type="r+" 或 type="w+" 以读写的方式打开文件file_rr=open("E:\\python\\hello_w.txt","r+");
# open(fileName,type) type="a+" 以追加和读写的方式打开文件file_aa=open("E:\\python\\hello_w.txt","a+");
二、python读取文件
#=====================python 文件读取方式 read()=====================# read() 读取全部 read(size) 读取指定数量的字符def readTest():
file_r=open("E:\\python\\hello.txt","r");
str=file_r.read();
print(str);
file_r.close();
#readline() 读取一行 readline(size) 读取一行中的size个字符(无论size是否大于一行的字符个数,总返回一行中的字符个数)def readLineTest():
file_r=open("E:\\python\\hello.txt","r");
str=file_r.readline(2);
print(str);
file_r.close();
# readLines() 读取全部文件(io.DEFAULT_BUFFER_SIZE),返回每一行所组成的列表(如果文件很大会很占用内存空间)def readLinesTest():
file_r=open("E:\\python\\hello.txt","r");
str=file_r.readlines(18);
print(str);
file_r.close();
#iter: 使用迭代器读取文件def IterTest():
file_r=open("E:\\python\\hello.txt","r");
iter_f=iter(file_r);#将文件转为迭代器, lines=0;
for line in iter_f:
print(line);
lines+=1;
print(lines);
file_r.close();
三、python写入文件
在介绍文件写入时,先了解一个文件缓存区的概念。
cpu在操作物理内存中的数据(读写)速度是很耗时的,我们的计算机为了提高运行效率,我们的计算机cup内核会对数据参数一个高速缓存区,cup会先操作高速缓存区中的数据,然会在某一时刻将高速缓存区中的数据写入到物理内存中。
所以在文件写入时我们不得不提两个方法 close() 与flush();
#=====================文件关闭 close()====================
# 将缓存数据写入磁盘
# 在linux系统中每个进程打开文件的个数是有限的(如果超过该限度,再打开文件就会失败)所以在每次使用完文件后一定要关闭该文件
#===================== flush()====================
# 将缓存数据写入磁盘
关于cpu缓存代码演示:
创建一个空文件hello.txt
def writerTest():
file=open("E:\\python\\hello.txt","w");
file.write("hello Word");
结果:hello.txt 还是为空