【发布时间】:2014-01-18 14:44:23
【问题描述】:
我有一个 6-7 行的文本文件 (test.txt)。其中3-4个有“例外”一词。同样在这3-4行中,其中2行还带有“abc”一词。我的任务是编写一个程序,通过其输出,我将能够分隔包含用户输入的任何单词的行(word1),但不能分隔包含(word1)和(word2)的行,例如“abc”:这也将是来自用户的输入)并将其写入新文件(test_mod.txt)。我必须从命令行参数执行此操作。所以这是我在命令提示符下的命令: “fileinput4.py test.txt test_mod.txt abc 异常” 此处包含“abc”和“exception”的行将被排除,仅包含“exception”一词的行将被包含并复制到 test_mod.txt 中。 到目前为止,我已经异常处理了以下事情: 1.如果两个单词相同,则显示错误消息。 2.如果少于5个参数显示错误消息。 3.如果第一个文件名拼写错误,则显示错误消息 4. 如果输入文件名和输出文件名相同,则显示错误消息。 如果有人输入了一些根本不在文本文件中的单词,我也想进行异常处理。但是我的代码中有一些错误,这件事没有发生。请帮助。每当我输入任何不在文件中的单词时,都不会打印任何内容,并且正在创建一个新文件,并且没有任何我想要阻止的错误消息。 这是我的代码:
import sys
import os
def main(): #main method
try:
f1 = open(sys.argv[1], 'r') #takes the first input file in command line
user_input1 = (sys.argv[3]) #takes the word which is to be excluded.
user_input2 = (sys.argv[4]) #takes the word which is to be included.
if sys.argv[1] == sys.argv[2]:
sys.exit('\nERROR!!\nThe two file names cannot be the same.')
if sys.argv[3] != sys.argv[4]:
for line in f1:
if user_input2 or user_input1 in line:
f2 = open(sys.argv[2], 'a')
if user_input1 in line:
if user_input2 in line:
pass
elif user_input2 in line:
f2.write(line)
else:
sys.exit('\nOne of the words or both of them does not exist.')
if sys.argv[3] == sys.argv[4]:
sys.exit('\nERROR!!\nThe word to be excluded and the word to be included cannot be the same.')
except IOError:
print('\nIO error or wrong file name.')
except IndexError:
print('\nYou must enter 5 parameters.')
except SystemExit as e:
sys.exit(e)
if __name__ == '__main__':
main()
【问题讨论】:
-
user_input2 or user_input1 in line应该是user_input2 in line or user_input1 in line。 -
您可以从学习
argparsemodule 中受益。此外,您可以使用grep完成此任务(如果您使用的是 linux/unix/osx)。此外,当单词不在文件中时,您应该考虑不要引发异常。为此,您需要在任何处理之前读取整个文件。您不妨在第一次读取文件时过滤这些行,然后在未找到输入时打印warning。 -
是的,这就是我添加 else 行的原因: sys.exit('\n其中一个或两个单词都不存在。') 但是代码没有进入该部分。我不知道为什么
-
确保您的缩进和空格是适当的。此外,如果第一行不包含
user_input2或user_input1,您将退出程序。如果您的程序没有输入else:子句,那么您可能实际上并没有提供满足该条件的输入!
标签: python file exception exception-handling