Python基础(五) Python文件操作

来源:互联网 发布:js 事件绑定区别 编辑:程序博客网 时间:2024/06/05 22:43

Python基础(五) Python文件操作

# -*- coding: UTF-8 -*-import osprint "文件管理"#打开文件def OpenFile(filepath,openWay):   print "****打开文件 "   print "*******文件名 : ",filepath,"打开方式 :",openWay   fo = open(filepath,openWay)   return fo;#读文件def ReadFile(fo,lenth):   print "****读文件"   str = fo.read(lenth)   print "*******读取到的内容为:", str    return str;#写文件def  WriteFile(fo,str):   print "****写文件"   fo.write(str);   return;#关闭文件def CloseFile(fo):   print "****关闭文件"   fo.close()   return#重命名def RenameFile(file_name,newname):   print "****重命名文件",file_name,"为 : ",newname   os.rename(file_name,newname)   return#删除文件def DeleteFile(file_name):   print "****删除文件 :",file_name   str = raw_input("是否确定删除文件Y/N:")   if str == "Y" or str == "y":      os.remove(file_name)      print file_name,"文件已被删除"   else:      print "该文件未被删除"   return;#输入字符串并写入文件def WriteFileByInput(filename):   print "****输入字符串并写入文件"   str = raw_input("请输入字符");   print "输入的字符串为 :",str   fo = OpenFile(filename,"a+")   WriteFile(fo,str)   CloseFile(fo)   return;#测试myPath = "test.txt"newPath = "newTxst.txt"fo = OpenFile(myPath ,"a+")WriteFile(fo,"I\'m writing string to this file !")# 把指针再次重新定位到文件开头position = fo.seek(0, 0);stringInFile = ReadFile(fo,120)CloseFile(fo)WriteFileByInput(myPath)RenameFile(myPath,newPath)DeleteFile(newPath)

复制文件
import shutildef copyfile(filepath,newpath):if os.path.exists(newpath):os.remove(newpath)print "delete ",newpathshutil.copyfile(filepath, newpath)print "copy %s to %s successful" % (filepath,newpath)



0 0
原创粉丝点击