【发布时间】:2016-05-27 23:14:39
【问题描述】:
我正在编写一个 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' 将是输出文件,我建议创建它的代码以防文件不存在。在我把这段代码放到类中之前它就起作用了......
【问题讨论】:
-
你在哪里调用排序、反向或随机播放?我无法重现您的错误。另外,我不明白你为什么使用 %s 写入文件,
item已经是一个字符串,为什么你用 "wb" 打开?最后查看this question了解其他读取源文件的方式。 -
我目前还没有调用 sort、reverse 或 shuffle,只是通过创建 'Xiv' 类的 'x' 实例来调用 init。我正在使用 %s 和“wb”,因为我从我找到的一些示例中获取它并且它之前工作过;)无论如何,我的问题是为什么输出文件会出现错误?它不是要从磁盘读取的源文件..
-
实际上要让它工作,我必须删除
type=file。它给了我NameError: name 'file' is not defined -
请显示整个回溯。这包括有价值的信息,例如发生错误的行。另外,请注意您的
sort()方法将引发NameError异常,因为source变量将未定义 -
这个问题How to open file using argparse?暗示
type=file不是你应该做的。