2012-09-24 73 views
0

我有一個文本文件(test.txt的),其中包含Python的 - 保持命令窗口打開看到的結果

text1 text2 text text text 

下面是我的代碼:

import codecs 
BOM = codecs.BOM_UTF8.decode('utf8') 
name = (raw_input("Please enter the name of the file: ")) 

with codecs.open(name, encoding='utf-8') as f: 
    words=[]   #define words here 
    for line in f: 
     line = line.lstrip(BOM) 
     words.extend(line.split())  #append words from each line to words 

if len(words) > 2: 
    print 'There are more than two words' 
    firstrow = words[:2] 
    print firstrow    #indentation problem here 
elif len(words) <2:     #use if 
    print 'There are under 2 words, no words will be shown' 

raw_input("Press return to close this window...") 

當我運行.py文件,我想讓命令窗口保持打開狀態,以便我可以看到所有打印件,但由於某種原因,它會立即關閉,當我在shell中運行它時,它會起作用。對於某些推理,raw_input不像我通常那樣工作。我的第二天在python,所以我仍然是一個新手!

在此先感謝幫助

+0

機會是你的原始輸入之前的某個地方有一個錯誤... –

回答

1

新手問題,新手回答!

我沒有在我的.py目錄中的我的文本文件只在我的shell路徑,這就是爲什麼它在那裏工作。

1

您應該至少將文件讀取代碼放在try/except塊中,以便您可以看到發生了什麼錯誤;

import codecs 

BOM = codecs.BOM_UTF8.decode('utf8') 
name = raw_input("Please enter the name of the file: ") 

try: 
    with codecs.open(name, encoding='utf-8') as f: 
    words=[]   #define words here 
    for line in f: 
     line = line.lstrip(BOM) 
     words.extend(line.split()) 
except Exception as details: 
    print "Unexpected error:", details 
    raw_input("Press return to close this window...") 
    exit(1) 

if len(words) > 2: 
    print 'There are more than two words' 
    firstrow = words[:2] 
    print firstrow 
elif len(words) <2:     #use if 
    print 'There are under 2 words, no words will be shown' 

raw_input("Press return to close this window...") 

如果我嘗試這與一個不存在的文件名:

Please enter the name of the file: bla 
Unexpected error: [Errno 2] No such file or directory: 'bla' 
Press return to close this window... 
相關問題