Python文件无法打开文件?

use*_*884 -1 python text exception

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

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()
Run Code Online (Sandbox Code Playgroud)

我检查文件名是否拼写正确,它是,并且该文件与python文件在同一目录中,我之前使用过这段代码.为什么不起作用?

Ion*_*lub 6

independence是一个字符串列表.你不能在列表上调用strip.试试这个:

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
Run Code Online (Sandbox Code Playgroud)