gpt4 book ai didi

python - IO错误 : [Errno 2] No such file or directory error is presented for the ouptup file

转载 作者:行者123 更新时间:2023-11-28 16:30:47 25 4
gpt4 key购买 nike

我正在编写 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' 将成为输出文件,我建议使用代码创建它以防文件不存在。在我将这段代码放入类之前它就起作用了....

最佳答案

在 Python 2 中,当我在一个不存在的文件上调用 file 时,我得到这个错误:

In [13]: file('out.txt')
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-13-d0d554b7d5b3> in <module>()
----> 1 file('out.txt')

IOError: [Errno 2] No such file or directory: 'out.txt'

在Py2中,file等同于open。它打开一个文件,默认为 r 模式,因此如果文件不存在将给出此错误。

argparse 中,type=foo 表示使用输入字符串运行函数foo。它并不意味着“将字符串解释为这种类型的对象”。

在您的代码中:

with open(dist, 'wb') as f2:  
for item in list2:
f2.write("%s" % item)

这意味着您希望 dist 是一个文件名,一个字符串。您不希望解析器先打开文件。你自己在做。所以不要指定 type 参数。

@tmoreau - Python3 删除了 file 函数,只留下 open

关于python - IO错误 : [Errno 2] No such file or directory error is presented for the ouptup file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32143595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com