带导入modu的Python索引器

2024-09-30 20:37:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的脚本,这是运行相当不错,直到目前为止,对pyhthon 2.7的日期

#!/usr/bin/python
# Python code Just to list the information from passwd file to obtain diffrent feilds out of it eg: UserName,GUID,UID,HomeDir,Shell etc.
# We will be using File-handling to obtain the Desired data.
# We have used 'Myfh' as a File-handler ,The open() function opens and returns a file handle that can be used to read or write a file in the usual way.
# Here we have '/tmp/passwd' file to get the data from it & 'r' is read-Only option to do it.
# We either used split fucntion to split the ":" from the file and opt for desired feild.

Myfh = open('/tmp/passwd', 'r')

for line in sorted(Myfh.readlines()):
        a = line.strip().split(":")
        """print "User Name: ", a[0]
        print 'User UID: ', a[2]
        print 'User GID: ', a[3]
        print 'User Gecos: ', a[4]
        print 'User HomeDir: ', a[5]
        print 'Users Shell: ', a[6]
        """
        print '| %-17s |%-10s | %-10s | %-28s | %-24s | %-15s |' % (a[0],a[2],a[3],a[4],a[5],a[6])

# ls -l /usr/bin/python
-rwxr-xr-x 2 root root 8304 Jun 11  2009 /usr/bin/python

# python  labPasssort.py
Traceback (most recent call last):
  File "labPasssort.py", line 20, in <module>
    print '| %-17s |%-10s | %-10s | %-28s | %-24s | %-15s |' % (a[0],a[2],a[3],a[4],a[5],a[6])
IndexError: list index out of range

你知道吗============= 当我尝试在python提示符“>;>;”上导入以下两个时,我觉得这不起作用。有人能找出这个。。。你知道吗

from os import listdir from os.path import isfile, join

请帮帮我,我是初学者。。你知道吗


Tags: thetoinfrombinusritused
2条回答

你确定a的长度是7吗? 因为该错误意味着您正试图访问超出列表长度的项。你知道吗

打印a以查看实际长度。你知道吗

谢谢你的时间和分析。。。。虽然我得到了错误,因为我发现错误“/tmp/passwd”文件本身,因为有最初的几行是损坏的输出,无法读取它。。重新检索文件后,脚本正常工作。。。你知道吗

相关问题 更多 >