Python:从命令行参数

时间:2017-04-23 15:45:45

标签: python python-2.7

我正在编写一个简单的脚本来计算从谷歌表单生成的csv文件中的一些值。

脚本如下:

import csv
import os.path

fileName=None

if __name__=="__main__":
    try:
        fileName=argv[1]
        isFile(fileName)
        pass
    except Exception as e:
        print("You must provide a valid filename as parameter")
        raise

def isFile(fileName):
    if(not os.path.isfile(fileName)):
        raise ValueError("You must provide a valid filename as parameter")

print fileName


def readCsvAndCountPercentPerFormItemFromGoogleForms(fileName):
    times={}
    totalRows=0
    with open(fileName,'r') as csvfile:

        csvReader=csv.reader(csvfile);

        for row in csvreader:

            value=row[1]

            if(value in times.values()):
                times[value]+=1
            else:
                times[value]=1

            totalRows+=1

        return calculateDictionaryAsPercent(times,totalRows)

def calculateDictionaryAsPercent(times,totalRows):

    if(totalRows==0):
        raise ValueError("The file does not contain any rows")

    for key,val in times.items():
            times[key]=(val/totalRows)*100

    return times


finalTimes=readCsvAndCountPercentPerFormItemFromGoogleForms(fileName)

print finalTimes

但是我收到以下错误:

Traceback (most recent call last):
  File "csv.py", line 1, in <module>
    import csv
  File "/home/pcmagas/Kwdikas/python/csv.py", line 54, in <module>
    finalTimes=readCsvAndCountPercentPerFormItemFromGoogleForms(fileName)
  File "/home/pcmagas/Kwdikas/python/csv.py", line 26, in readCsvAndCountPercentPerFormItemFromGoogleForms
    with open(fileName,'r') as csvfile:
TypeError: coercing to Unicode: need string or buffer, NoneType found

问题在于,由于某种原因,变量fileName不会改变以下值:

if __name__=="__main__":
    try:
        fileName=argv[1]
        isFile(fileName)
        pass
    except Exception as e:
        print("You must provide a valid filename as parameter")
        raise

以下一段代码基于Detect and print if no command line argument is provided

上找到的第一个答案

所以你能给我一个解决方案,因为我不经常编写python,因此我做了以下脚本以便更好地学习它。

编辑1

代码已重新格式化为:

import csv
from sys import argv
import os.path


def isFile(fileName):
    if(not os.path.isfile(fileName)):
        raise ValueError("You must provide a valid filename as parameter")


def readCsvAndCountPercentPerFormItemFromGoogleForms(fileName):
    times={}
    totalRows=0
    with open(fileName,'r') as csvfile:

        csvReader=csv.reader(csvfile);

        for row in csvreader:

            value=row[1]

            if(value in times.values()):
                times[value]+=1
            else:
                times[value]=1

            totalRows+=1

        return calculateDictionaryAsPercent(times,totalRows)

def calculateDictionaryAsPercent(times,totalRows):

    if(totalRows==0):
        raise ValueError("The file does not contain any rows")

    for key,val in times.items():
            times[key]=(val/totalRows)*100

    return times


fileName=None

if __name__=="__main__":
    try:
        fileName=argv[1]
        print("Filename: ",fileName)
        isFile(fileName)
        pass
    except Exception as e:
        print("You must provide a valid filename as parameter")
        raise

print("Filename: ",fileName)
finalTimes=readCsvAndCountPercentPerFormItemFromGoogleForms(fileName)

print finalTimes

仍然是同样的错误。

2 个答案:

答案 0 :(得分:-1)

你有这一行:

fileName=argv[1]

应该是:

fileName=sys.argv[1]

更不用说你甚至没有导入sys

另外,作为备注,我更喜欢argparse

答案 1 :(得分:-1)

最后提到的脚本应该是这个:

import csv
from sys import argv
import os.path


def readCsvAndCountPercentPerFormItemFromGoogleForms(fileName):
    times={}
    totalRows=0
    with open(fileName,'r') as csvfile:

        csvReader=csv.reader(csvfile);

        for row in csvReader:

            value=row[1]

            if(value in times.values()):
                times[value]+=1
            else:
                times[value]=1

            totalRows+=1

        return calculateDictionaryAsPercent(times,totalRows)

def calculateDictionaryAsPercent(times,totalRows):

    if(totalRows==0):
        raise ValueError("The file does not contain any rows")

    for key,val in times.items():
            times[key]=(val/totalRows)*100

    return times


def isFile(fileName):
    if(not os.path.isfile(fileName)):
        raise ValueError("You must provide a valid filename as parameter")

fileName=None

if __name__=="__main__":
    try:
        fileName=argv[1]
        isFile(fileName)
        pass
    except Exception as e:
        print("You must provide a valid filename as parameter")
        raise

finalTimes=readCsvAndCountPercentPerFormItemFromGoogleForms(fileName)

print finalTimes