文件:读取,写入
流:stream(字节流,字符流,缓存流)
从文件(磁盘)到项目(内存) 读取【输入流input】
从项目到文件 写入【输出流output】
过程:创建文件对象(路径,文件名)<读取<关闭
open(fliename,mode)创建
mode(
r只读
rb以二进制制度
r+读写
rb+ (b)以二进制读写
w写,存在覆盖,不存在创建
wb
a追加
a+
ab+
) 读取一个文件
myflie=open("G:/text.txt","r+")
print(myflie.read(20))
myflie.close() 写一个文件
qw=open("G:/qw.txt","w")
str='qwe'
wq=qw.write(str)
print(wq)
qw.close()
qw=open("G:/qw.txt","w")
str=['qwe','ert']
for i in str:
print(qw.write(i))
qw.close()
文件的复制
ww=open("G:/qw.txt","r")
ww1=open("G:/word.txt","w")
qq=ww.read()
ww1.write(qq)
ww1.close()
ww.close()
myread=open("G:/bbb.txt","r")
mywrite=open("G:/ccc.txt","w")
mystr=myread.read(1024)
while len(mystr)>0:
mywrite.write(mystr)
mystr = myread.read(1024)
mywrite.flush()
mywrite.close()
myread.close() file.close file.flush刷新文件内部缓冲,针对文件写入 file.next返回文件下一行 file.read([size])读取指定大小字节 read缩写r+ file.readline()读取整行 file.readlines()读取所有行 file.seek(0,2)从第几行开始读取 从文件末尾开始 (0,0)从文件开头 (0,1)从文件当前位置 file.tell()返回当前位置 file.truncate(10)截断, file.write(str) os改变当前工作目录 os.open(flie,flags) os.open('ccc.txt',os.O_APPEND) flags( os.O_APPEND ) os.rename('旧文件名','新文件名') os.mkdir('')创建文件夹 os.rmdir('')删除文件夹 os.getcwd()得到当前路径 os.listdir('./')得到当路径下所有文件,返回一个文件集 import os os.mkdir('G:/os') #获取一个文件名的后缀 def getfile_fix(filename): return filename[filename.rfind('.')+1:] print(getfile_fix('runoob.txt')) #循环 myread=open('bbb.txt','r') for line in myread: print(line,end='') myread.close()''' #写 执行完自动结束 with open (
'bbb.txt' ,
'w' ,
encoding =
'utf-8' )
as f:
print (f.write(
'bbb' ))
#读 with open (
'yui.txt' ,
'r' ,
encoding =
'utf-8' )
as f:
print (f.readlines())
爬虫代码
from urllib import request #请求
response=request.urlopen("http://www.baidu.com/" )#打开网站
fi=open ("project.txt" ,'w' ) #打开一个txt文件
page=fi.write(str (response.read())) #网站代码写入
fi.close()