文件: 计算机的数据存储在硬盘上 文件的作用:
在python中,使用open函数,可以打开一个已经存在的文件,或者创建一个新的文件。 open(文件名,访问模式) eg:f = open(‘test.txt’,‘w’) 如果文件不存在那么创建,如果存在那么就先清空,然后写入数据 要读取二进制文件,比如图片、视频等等,用‘rb’,‘wb’,‘ab‘ 等模式打开文件即可
========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first(1).文件不存在则创建文件; 2).文件存在, 清空文件内容) 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists(1).文件不存在则创建文件; 2).文件存在, 不会清空文件内容) 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== 是否有读权限? 是否有写权限? 文件不存在,是否会创建文件? 文件操作会清空文件内容么? r yes no no no w no yes yes yes a no yes yes no w+ yes yes yes yes a+ yes yes yes no r+ yes yes no no f = open('txt/hello','a+') print(f.mode) ##此时读取不到文件内容是因为文件索引在文件最后,后面什么也没有 print(f.read()) f.seek(0,0) print(f.read()) f.write('hahahaha') ##在文件里写入 f.close() ##关闭文件
方法一:调用close()方法关闭文件。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的;
方法二:Python 引入了with语句来自动帮我们调用close()方法:
python中的with语句使用对资源进行访问的场合,保证不管处理过程中是否发生错误或者异常都会自动执行规定的(“清理”)操作,释放被访问的资源,比如有文件读写后自动关闭、线程中锁的自动获取和释放等。
""" with语句工作原理: python中的with语句使用于对资源进行访问的场合, 保证不管处理过程中是否发生错误或者异常都会自动 执行规定的(“清理”)操作,释放被访问的资源, 比如有文件读写后自动关闭、线程中锁的自动获取和释放等。 """ with open('txt/hello-备份') as f: print('with语句里面:',f.closed) print(f.read(5)) print('with语句外面:',f.closed)
输入文件的名字,然后程序自动完成对文件的备份。
import os """ 实现拷贝文件的操作 思路: cp img/passwd(source_file) txt/hello(dst_file) (1)判断拷贝的文件是否存在? (2)如果存在,将源文件的内容读出来,写入目标文件 """ def copy(source_file,dst_file): if os.path.exists(source_file): #将源文件的内容读取出来 f = open(source_file) content= f.read() f.close() #写入目标文件 dst_file= open(dst_file,'w') dst_file.write(content) dst_file.close() print("拷贝%s为%s成功"%(source_file,dst_file)) else: print("源文件%s不存在"%(source_file)) copy('img/passwd' , 'txt/hello-备份' )