-1

だから私はこのコードを持っていて、ファイルを開こうとしています。ただし、コードの例外部分は常に実行されます。

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 ファイルと同じディレクトリにあり、以前にこのコードを使用したことがあります。なぜ機能しないのですか?

4

1 に答える 1

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
于 2013-03-04T15:50:18.930 に答える