Python sys.argv[1],索引器:列表索引超出范围

Python sys.argv[1],索引器:列表索引超出范围,python,Python,我对Python代码的以下部分有问题: # Open/Create the output file with open(sys.argv[1] + '/Concatenated.csv', 'w+') as outfile: try: with open(sys.argv[1] + '/MatrixHeader.csv') as headerfile: for line in headerfile: outfile

我对Python代码的以下部分有问题:

# Open/Create the output file
with open(sys.argv[1] + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(sys.argv[1] + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'
具体错误如下:

Traceback (most recent call last): File "ConcatenateFiles.py", line 12, in <module> with open(sys.argv[1] + 'Concatenated.csv', 'w+') as outfile:
IndexError: list index out of range
Traceback(最后一次调用):文件“ConcatenateFiles.py”,第12行,以open(sys.argv[1]+'Concatenated.csv','w+')作为输出文件:
索引器:列表索引超出范围
我做了一些研究,似乎在运行脚本时,
sys.argv
可能需要在命令行中使用一个参数,但我不确定要添加什么或问题是什么!我也搜索过这个网站,但我找到的所有解决方案要么没有评论,要么没有像我一样包含open函数


非常感谢您的帮助。

sys.argv
表示执行脚本时使用的命令行选项

sys.argv[0]
是正在运行的脚本的名称。所有附加选项都包含在
sys.argv[1:][/code>中

您正试图打开一个文件,该文件使用
sys.argv[1]
(第一个参数)作为目录

尝试运行类似以下内容:

python ConcatenateFiles.py /tmp
我做了一些研究,似乎sys.argv在运行脚本时可能需要在命令行中使用一个参数

不可能,但肯定需要。这就是sys.argv的全部要点,它包含命令行参数。与任何python数组一样,访问不存在的元素会引发
索引器

虽然代码使用
try/except
来捕获一些错误,但有问题的语句出现在第一行

因此,脚本需要一个目录名,您可以通过查看
len(sys.argv)
并与1+numberofu需求进行比较来测试是否有目录名。argv始终包含脚本名和任何用户提供的参数,这些参数通常以空格分隔,但用户可以通过引用覆盖空格分隔。如果用户未提供参数,则您的选择是提供默认值、提示用户或打印退出错误消息

要打印错误并在缺少参数时退出,请在首次使用sys.argv之前添加此行:

if len(sys.argv)<2:
    print "Fatal: You forgot to include the directory name on the command line."
    print "Usage:  python %s <directoryname>" % sys.argv[0]
    sys.exit(1)

if len(sys.argv)
sys.argv
是传递给Python脚本的命令行参数列表,其中
sys.argv[0]
是脚本名称本身

它出错是因为您没有传递任何命令行参数,因此
sys.argv
的长度为1,因此
sys.argv[1]
超出范围

要“修复”,只需确保在运行脚本时传递命令行参数,例如

python ConcatenateFiles.py /the/path/to/the/directory
但是,您可能希望使用一些默认目录,以便在不传入目录时仍能工作:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

应该是
python concatenatefile.py
。这是假设你正在做一个
导入系统
的第一步,这是成功的,软的!现在我得到‘No header File’。您调用的第二个
open
语句没有指定打开模式。默认情况下,以只读方式打开文件,如果文件不存在,将失败。您需要将其更改为
,以open(sys.argv[1]+'/MatrixHeader.csv',w')作为标题文件:
cur_dir=sys.argv[1]if len(sys.argv)>1 else.
这是我一直在寻找的,我找到了它。如果你不想通过辩论,你不必这样做。谢谢@lemonhead