2017-12-20 4 views
0

Windows 터미널의 파일 small.txt에서 cat (filename) 함수를 읽고 수행 할 수 없습니다. 파이썬 스크립트의 이름은 hello.py입니다. hello.py small.txt를 실행해도 결과가 표시되지 않습니다. 스크립트 코드는 다음과 같습니다..py 스크립트를 사용하여 .txt 파일을 실행 중입니다.

import sys 
    def cat(filename): 
     f=open (filename,'rU') 
     text = f.read() 
     print text 
    def main(): 
     cat (sys.agrv[1]) 
    # This is the standard boilerplate that calls the main() function. 
    if __name__ == '__main__': 
     main() 

    RESTART: C:\Users\WELCOME\google-python-exercises\hello.py 

    Traceback (most recent call last): 
    File "C:\Users\WELCOME\google-python-exercises\hello.py", line 34, in <module> 
    main() 
    File "C:\Users\WELCOME\google-python-exercises\hello.py", line 30, in main 
    cat (sys.agrv[1]) 
    AttributeError: 'module' object has no attribute 'agrv' 
+0

agrv가 아님 –

+0

7 행에서 'argv'의 철자가 'agrv'로 잘못 입력되었습니다. – ikkuh

답변

0

맞춤법 오류 agrv이 있습니다. 파일을 읽은 후에는 파일을 닫지 않습니다. 이 시도 :

import sys 

def cat(filename):  
    f = open(filename) 
    text = f.read() 
    f.close() 
    print(text) 

def main(): 
    cat(sys.argv[1]) 

if __name__ == '__main__': 
    main() 

내가 그것을 파일을 닫는 돌봐로 with 문을 사용하여 cat() 기능을 다시 것입니다.

def cat(filename):  
    with open(filename) as f: 
     text = f.read() 
    print(text) 

Python Tutorial는 말한다 :

그것은 파일 객체를 처리 할 때 with 키워드를 사용하는 것이 좋습니다입니다. 장점은 파일이 예외 처리가 끝난 후에도 제대로 종료된다는 것입니다.

관련 문제