2012-08-01 53 views
1

有人可以幫助我,我試圖鏈接optparse與csv閱讀器,但我一直無法這樣做。以下是我的代碼:optparse csv.reader

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部分,以便用戶可以輸入文件名路徑。 謝謝!

我更新了我的代碼。仍然無法讓它工作。

UPDATE1:

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() 
+2

不要引用''input1file'',除非這是你想要的實際文件名。 – geoffspear 2012-08-01 15:48:10

+2

考慮切換到argparse。這些都是很酷的孩子們最近做的。 – mgilson 2012-08-01 15:53:16

+0

另外'optparse'已棄用。 – 2012-08-01 16:35:54

回答

1

如果你沒有在命令行上指定--i1options.input1fileNone,因爲你不提供一個默認值。

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建議,使用​​代替。它支持命名的位置參數。

+0

@ user1546610而不是在幫助文本中說「[REQUIRED]」,你可以傳遞'required = True'來實際執行它。 – Dougal 2012-08-01 16:18:14

+0

@Dougal - Nope,只適用於'argparse'。 'optparse'認爲「必需的選項」在英語中是矛盾的,因此所需的選項實際上應該是爭論。 – mgilson 2012-08-01 16:21:21

+0

我堅持使用2.6版本,所以我不能使用argparse。 – user1546610 2012-08-01 16:27:23

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) 

注意,這是比較容易做​​。你只是通過required=Trueadd_argument方法

+0

仍然無法使用。我試過了。它給了:TypeError:強制爲Unicode:需要字符串或緩衝區,沒有找到類型 – user1546610 2012-08-01 16:04:26

+0

@ user1546610 - 你是如何調用程序的? – mgilson 2012-08-01 16:12:48

+0

使用cmd窗口。 – user1546610 2012-08-01 16:16:26