Python:从空列表中弹出?

时间:2018-03-24 14:31:24

标签: python python-3.x list tuples

我试图编写一个简单的程序,它需要在一个文件中对数字进行排序并将输出写入另一个文件,但我无法做到。

from sys import argv
try:
    with open(argv[1],"r") as desti:
        with open("nums_ordenats.txt","w") as prl:
            for n in desti:
                argv.pop(0)
                argv.sort()
                argv.sort(key=len)
            prl.write(str(n)+("\n"))
except Exception as err:
    print(err, "Error")

有人可以解释一下错误在哪里?非常感谢!

2 个答案:

答案 0 :(得分:0)

您的方法无法正常工作,因为索引超出了范围,您可以执行以下代码来读取和排序文件中的数字。

from sys import argv    
with open(argv[1],'r') as myfile:
        for line in myfile:
            print (sorted(map(int, line.split(','))))

如果您的文件包含逗号分隔值。

答案 1 :(得分:0)

错误在行argv.pop(0)中,因为argv在运行时为空。这意味着destiargv[1])长于argv。 原因是argv的格式为['C:\\This\\is\\a\\path.py'],因此仅包含'C:\\This\\is\\a\\path.py'argv[1],  但是('C:\\This\\is\\a\\path.py')包含每个单独的字符,因为它是一个字符串。如果您想要每个文件夹(然后是文件),您可以使用: argv[1].split('\\'),将返回: ['C:', 'This', 'is', 'a', 'path.py']