Python基础(五) Python文件操作
# -*- coding: UTF-8 -*-
import os
print "文件管理"
#打开文件
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 shutil
def copyfile(filepath,newpath):
if os.path.exists(newpath):
os.remove(newpath)
print "delete ",newpath
shutil.copyfile(filepath, newpath)
print "copy %s to %s successful" % (filepath,newpath)