Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python文件未打开文件?_Python_Exception_Text - Fatal编程技术网

Python文件未打开文件?

Python文件未打开文件?,python,exception,text,Python,Exception,Text,所以我有这个代码,我试图让它打开一个文件。但是,代码的异常部分总是被执行 def main(): #Opens up the file try: fin = open("blah.txt") independence = fin.readlines() fin.close() independence.strip("'!,.?-") #Gets rid of the punctuation pri

所以我有这个代码,我试图让它打开一个文件。但是,代码的异常部分总是被执行

def main():
    #Opens up the file
    try:
        fin = open("blah.txt")
        independence = fin.readlines() 
        fin.close()
        independence.strip("'!,.?-") #Gets rid of the punctuation 
        print independence
        #Should the file not exist
    except:
        print 'No, no, file no here'

if __name__ == "__main__":
    main()

我检查了文件名的拼写是否正确,是否正确,并且该文件与python文件位于同一目录中,我以前使用过这段代码。为什么它不工作?

独立性是一个字符串列表。你不能给名单上的脱衣舞打电话。
试试这个:

def main():
    fin = open('blah.txt', 'r')
    lines = fin.readlines() 
    fin.close()
    for line in lines:
        print line.strip("'!,.?-")

if __name__ == '__main__':
    try:
        main()
    except Exception, e:
        print '>> Fatal error: %s' % e

请修正缩进!您可以打印异常并找出原因!:)正如Fredrik所说,由于缩进有点不正常,我们无法准确判断Python程序目前执行的是什么-您是否可以修复它,使其看起来像编辑器/IDE中的缩进?使用
,除了:
,未检查任何特定异常不会让您确信打开文件是失败的。首先,正如弗雷德里克所说:修正这个缩进!。第二,将except更改为
Exception作为e:
,然后在except子句中执行
打印(e)
,以查看引发了什么。实际上,您不应该使用基本异常-如果您想检查未找到的文件,请执行
除IOError as e之外的操作
,以检查这可能是错误的原因;当你使用它时,使用
和open(“blah.txt”)作为fd
而不是如果你没有在那里使用除了
以外的裸
,你会看到错误,因为你会有
属性错误
,而不是
文件错误