Python - 保持命令窗口打开以查看结果

时间:2012-09-24 16:23:57

标签: python python-2.7

我有一个包含

的文本文件(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的第二天,所以我还是一个新手!

提前感谢您的帮助

2 个答案:

答案 0 :(得分:1)

新手问题,新手回答!!

我的文本文件只在我的.py路径中没有。这就是为什么它在那里工作的原因。

答案 1 :(得分: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...