Python:当前路径下文件的复制

# -*- coding:utf-8 -*-
"""
实现一个文件拷贝的功能
"""
import os
import time

# 定义一个获取当前路径下所有文件的函数
def listFile():
    workPath = os.getcwd()
    return list(os.listdir(workPath))

#定义一个判断文件是否存在的函数
def existsFile(fileName):
    if os.path.exists(str(fileName)):
        return True
    else:
        print "File is not exists."
        return False

def currentDate():
    return time.strftime('%Y-%m-%d',time.localtime(time.time()))
'''
print "Current path:",workPath
countFile = list(os.listdir(workPath))
'''

print "Files list:\n", listFile()

originalName = raw_input("Enter the filename which you want to copy:\n\t")
if existsFile(originalName):    #使用函数
#if os.path.exists(str(originalName)):  #判断文件是否存在
    #读取文件
    with open(originalName) as orfile:
        context = orfile.readlines()
    #新文件生成规则
    goalName = originalName[:-4] +str("_") + currentDate() + str(".txt")

    #将源文件内容复制到目标文件
    with open(goalName, 'a') as toName:
        print >> toName, context
    print "Copy Done."
    print "\t", str(originalName), "has been copied to", str(goalName)


#测试
if __name__ == '__main__':
    answerList = ("Y","y","N","n")  #定义一个tuple,存储两种选项
    if existsFile(originalName):
        print "\nWould you want to read the file after copied?"
        print "\t'Y':Read \t'N':No"
        answer = raw_input()
        if answer in answerList[:2]:
            with open(goalName) as copiedFile:
                print copiedFile.readlines()
        elif answer in answerList[2:len(answerList)]:
            print "You have choosen 'N',See you!"
        else:
            print "Other key has been nocked,copied file will not be opened."
    else:
        pass
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值