Python探索记(18)——文件File
来源:互联网 发布:扬州mac维修 编辑:程序博客网 时间:2024/06/08 17:37
# @Time : 2017/7/8 21:10# @Author : 原创作者:谷哥的小弟# @Site : 博客地址:http://blog.csdn.net/lfdfhl# @DESC : 文件File相关操作'''文件操作的主要流程1 打开或者创建文件2 读写文件3 关闭文件'''f=open('testFile.txt','w')f.write('大家好,这里是Python的学习笔记 \n 人生苦短,我用python')f.close()f=open('file1.txt','w')f.write('java,php,python')f.close()f=open('file2.txt','w')f.write('C++ C#')f.close()f=open('testFile.txt','r')content=f.read()print('content=',content)f.close()'''利用readlines()读取文件该方法可按照行的方式把整个文件中的内容进行一次性读取返回一个列表,其中每一行的数据为列表的一个元素'''f=open('testFile.txt','r')contentList=f.readlines();print('contentList的类型为:',type(contentList))i=1for content in contentList: print('第%i的内容为%s'%(i,content)) i+=1f.close()'''利用readline()读取文件该方法每次只读取一行,若继续调用该方法则从上次读取的位置继续读取'''f=open('testFile.txt','r')content=f.readline();print('content:',content)content=f.readline();print('content:',content)f.close()'''利用rename()重命名文件请注意需要引入 os'''import os#判断文件是否存在isExists=os.path.exists('newTestFile.txt')if not isExists: os.rename('testFile.txt','newTestFile.txt')'''文件夹的相关操作'''import os#创建文件夹isExists=os.path.exists('testpython')if not isExists: os.mkdir('testpython')#获取当前目录cwd=os.getcwd()print('cwd',cwd)#获取目录列表dirList=os.listdir('./')for d in dirList: print('d=',d)'''利用shutil.copy()复制文件利用shutil.copytree()复制文件夹'''import shutil#复制文件shutil.copy('file2.txt','file22.txt')#复制文件夹shutil.copytree('testpython','testpython2')'''利用remove()删除名文件利用rmdir()删除文件夹请注意需要引入 os'''import osos.remove('file1.txt')os.rmdir('testpython')
阅读全文
0 0
- Python探索记(18)——文件File
- Python探索记(02)——变量
- Python探索记(06)——while
- Python探索记(07)——for
- Python探索记(17)——函数
- Python探索记(15)——Python内置函数
- Python文件\文件夹操作—OS, File, Shutil
- [python]File文件操作
- Python File(文件) 方法
- Python探索记(03)——输入和输出
- Python探索记(04)——运算符
- Python探索记(05)——if和else
- Python探索记(08)——break和continue
- Python探索记(09)——字符串(上)
- Python探索记(10)——字符串(下)
- Python探索记(11)——列表List
- Python探索记(12)——元组Tuple
- Python探索记(13)——字典Dictionary
- LeetCode
- Swift 3 点击屏幕任意位置隐藏键盘
- C语言重点知识复习1
- 使用下面这些工具和技巧,帮你快速开发一个Android App
- 几个java小问题代码(大神不喜勿喷)
- Python探索记(18)——文件File
- 最大子数组 III
- 在Ubuntu(各个版本)上安装virtualbox
- 美团复赛 城市网络 (双倍增)
- shell命令代换与eval命令
- 在Ubuntu上安装virtualbox
- 你那么厉害还不是要进来看我用For循环判断一个数是否是素数。
- 免费ARP
- 2017北大信科机试C