0

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

在此先感谢您的帮助

4

2 回答 2

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...
于 2012-09-24T17:23:27.403 回答
1

新手问题,新手回答!!

我的 .py 目录中没有我的文本文件,仅在我的 shell 路径中,这就是它在那里工作的原因。

于 2012-09-24T16:27:29.570 回答