• python 编程测试练习答案


    encoding: utf-8

    '''


    '''

    import os

    从文本(txt)中读内容

    def readDataFromTxt(path):

    contents=""
    
    if os.path.exists(path):
    
        try:
    
            fr=open(path,'r')
    
            contents=fr.read()
    
            fr.close()
    
        except IOError:
    
            print "提示:A文件不存在,或者读取出现异常!"
    
    else:
    
        print "提示:文件"+path+"不存在,请输入正确路径!"
    
    return contents
    

    将内容写入到指定文件(txt)中

    def writeDataToTxt(path,mytxt):

    if os.path.exists(path): 
    
        try:
    
            fw=open(path,'a+')
    
            fw.write(mytxt+"
    ")
    
            fw.close()
    
        except IOError:
    
            print "提示:B文件不存在,或者读取出现异常!"           
    
    else:
    
        print "提示:文件"+path+"不存在,创建该文件!"
    
        fw=open(path,"a+")
    
        fw.write(mytxt+"
    ")
    
        fw.close()
    

    将A文件的内容写入到B文件中

    def writeAFile2BFile(aPath,bPath):

    mytxt=readDataFromTxt(aPath) 
    
    if mytxt:                                   #调用方法读取A文件(txt)的内容
    
        print "A中的内容:
    " +mytxt            
    
        writeDataToTxt(bPath,mytxt)             #调用方法往B文件(txt)写入内容
    
        mytxtB=readDataFromTxt(bPath)
    
        print "B中的内容:
    " +mytxtB
    
    else:
    
        print "提示:A中的内容为空:
    " 
    

    主函数

    if name == 'main':

    currentPath=os.getcwd()                    #获取当前路径
    
    aPath =currentPath+"\A.txt"               #拼接A文件的路径
    
    bPath =currentPath+"\B.txt"             
    
    writeAFile2BFile(aPath,bPath)
    
    pass
  • 相关阅读:
    ATM代码及遇到的问题总结
    暑假日报-52
    暑假日报-51
    暑假日报-50
    暑假日报-49
    暑假日报-48
    线段树优化建图(炸弹 + 选课)
    联考day2 C. 舟游
    联赛模拟测试5题解
    第19周作业
  • 原文地址:https://www.cnblogs.com/ITniu/p/6428494.html
Copyright © 2020-2023  润新知