且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python探索记(18)——文件File

更新时间:2021-12-14 06:07:15

# @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=1
for content in contentList:
    print('第%i的内容为%s'%(i,content))
    i+=1
f.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 os
os.remove('file1.txt')
os.rmdir('testpython')