簡體   English   中英

Python - 保持命令窗口打開以查看結果

[英]Python - Keep command window open to see results

我有一個包含的文本文件(test.txt)

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的第二天,所以我還是一個新手!

先謝謝您的幫助

新手問題,新手回答!!

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

您應該至少將文件讀取代碼放在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...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM