【问题标题】:optparse csv.readeroptparse csv.reader
【发布时间】:2012-07-30 13:31:46
【问题描述】:

有人可以帮助我吗,我正在尝试将 optparse 与 csv 阅读器链接,但我一直无法这样做。以下是我的代码:

import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

data = csv.reader(open('input1file','r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

我不知道如何连接 add_option 部分,以便用户可以输入文件名路径。 谢谢!

我更新了我的代码。但是还是不能正常工作。

更新1:

import sys
import csv
from optparse import OptionParser

parser = OptionParser()
parser.add_option('--i1', action='store', type='string', dest='input1file', help='[REQUIRED] The input .csv file path.')
(options, args) = parser.parse_args()
input1file = options.input1file

try:
    input1file = args[1]
except IndexError:
    sys.exit("Input file required, none given")

data = csv.reader(open(sys.args[1],'r'))
temp = open('C:\Practice\output_edited.csv','a')
for column in data:
    temp.write(column[0]+','+column[len(column)-1]+'\n')
    print column[0]+','+column[len(column)-1]+'\n'
temp.close()

【问题讨论】:

  • 不要引用 'input1file',除非那是您想要的实际文件名。
  • 考虑切换到 argparse。这就是现在所有酷孩子都在做的事情。
  • optparse 也已弃用。
  • 去掉try/except语句,使用data = csv.reader(open(input1file, 'r'))

标签: python csv path optparse


【解决方案1】:
data = csv.reader(open('input1file','r'))

应该是

data = csv.reader(open(input1file,'r'))

根据您的评论,您似乎忘记使用 --i1 参数。如果确实需要,您应该强制执行:

例如:

if not input1file:
  print "What?  you were supposed to give '--i1 filename', but you didn't.  Shame on you!"
  sys.exit(1)

请注意,这在argparse 中更容易做到。你只需将required=True 传递给add_argument 方法

【讨论】:

  • 还是不行。我试过了。它给出了:TypeError:强制转换为 Unicode:需要字符串或缓冲区,找不到类型
  • @user1546610 -- 你是怎么调用程序的?
  • @user1546610 -- 是的,但你是叫它myprogram -i1 myfile 还是叫myprogram
【解决方案2】:

如果你没有在命令行中指定--i1,那么options.input1file就是None,因为你没有提供默认值。

myscript.py --i1 input.txt

因为--i1 是必需的,所以它真的不应该是一个选项(因为它不是可选的)。从args 获取输入文件,而不是:

parser = OptionParser()
(options, args) = parser.parse_args()
try:
    input1file = args[0]
except IndexError:
    sys.exit("Input file required, none given")

或者,按照 mgilson 的建议,改用 argparse。它支持命名的位置参数。

【讨论】:

  • @Dougal -- 不,仅适用于argparseoptparse 的立场是“必需选项”在英语中是矛盾的,因此必需选项实际上应该是参数。
  • 我坚持使用 2.6 版,所以我不能使用 argparse。
  • @mgilson 啊,好点子。我已经很长时间没有真正使用optparse 并且忘记了那个愚蠢。
猜你喜欢
  • 2011-11-22
  • 2017-01-20
  • 1970-01-01
  • 2019-06-17
  • 2011-08-29
  • 2013-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多