我正在编写一个Python代码来操作文本文件。该代码将从命令行接收输入文件名和输出文件名以及一个标志(-sort,-reverse等),根据要在输入文件上应用的操作进行操作,并最终将数据写入输出文件。我需要在一个类内完成所有这些工作,以便代码可以被继承。到目前为止,我的代码如下:
现在当我运行它时,
import argparse
import random
class Xiv(object):
def __init__(self):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-s", "-sort", action="store_true")
group.add_argument("-r", "-reverse", action="store_true")
group.add_argument("-sh", "-shuffle", action="store_true")
parser.add_argument("inputfile", type = file, help="Input file name")
parser.add_argument("outputfile", type = file, help="Output file name")
args = parser.parse_args()
source =args.inputfile
dist = args.outputfile
def sort(self):
f = open(source, "r")
list1 = [line for line in f if line.strip()]
f.close()
list.sort()
with open(dist, 'wb') as fl:
for item in list:
fl.write("%s" % item)
def reverse(self, source, dist):
f = open(source, "r")
list2 = [line for line in f if line.strip()]
f.close()
list2.reverse()
with open(dist, 'wb') as f2:
for item in list2:
f2.write("%s" % item)
def shuffle(self, source, dist):
f = open(source, "r")
list3 = [line for line in f if line.strip()]
f.close()
random.shuffle(list3)
with open(dist, 'wb') as f3:
for item in list3:
f3.write("%s" % item)
x = Xiv();
现在当我运行它时,
python xiv.py -s text.txt out.txt
出现以下错误:
IOError: [Errno 2] No such file or directory 'out.txt'
但是'out.txt'
将成为输出文件,我建议在需要时创建该文件以防文件不存在。在我将此代码放入类之前,它曾经起作用过...
item
已经是一个字符串了,而且为什么要用“wb”打开?最后,请参考这个问题以了解读取源文件的其他方法。 - Meltype=file
。它给了我一个NameError: name 'file' is not defined
的错误。 - Melsort()
方法将引发NameError
异常,因为source
变量未定义。 - holdenwebtype=file
并不是你该做的事情。 - Melx =
Xiv()`。我看到了您提到的那个问题,但没有找到解决我的问题的答案;( - Prophet