如何访问try块的文件指针到else块python

时间:2017-12-28 12:04:42

标签: python

在下面的程序中,我在try块之外声明了fptr,因为我想将文件关闭到else块中。但得到"属性错误:' NoneType'对象没有属性' close' &#34 ;.如何关闭在这种情况下在try块中打开的文件

def openFile(fileName):
    fptr = open(fileName,"r")
    fptr.close()

def creatNewFile():
    fileName = input("Enter file name : ")
    fptr = open(fileName,"w")
    fptr.close()

def main():
    fileName = input("Enter file name with extension: ")
    fptr = 0
    try:
        fptr = openFile(fileName)
    except Exception as ex:
        print("File is not exist")
        choice  = input("Do you want to create new file(Y/N)")
        if((choice == 'N') or (choice == 'n')):
            print("Exiting program");
            exit(0)
        elif((choice == 'Y' or choice == 'y')):
            creatNewFile()

        else :
            print("Invalid choice, exiting program ")
    else:               
        fptr.close();

main()

1 个答案:

答案 0 :(得分:1)

您没有在 openFile() createNewFile()中返回文件对象。

试试这个:

def openFile(fileName):
    fptr = open(fileName, "r")
    return fptr


def creatNewFile():
    fileName = input("Enter file name : ")
    fptr = open(fileName, "w")
    return fptr


def main():
    fileName = input("Enter file name with extension: ")
    fptr = 0
    try:
        fptr = openFile(fileName)
        fptr.close()
    except Exception as ex:
        print("File is not exist")
        choice = input("Do you want to create new file(Y/N)")
        if ((choice == 'N') or (choice == 'n')):
            print("Exiting program")
            exit(0)
        elif ((choice == 'Y' or choice == 'y')):
            newfptr = creatNewFile()
            newfptr.close()
        else:
            print("Invalid choice, exiting program ")


main()