下面的脚本在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提示符">>“..can下导入以下两个文件时,我觉得这种方法不起作用--有人想出了.
从os导入从os.path导入isfile的listdir,加入
请帮帮我,我是初学者。
发布于 2015-12-10 14:19:59
你确定a的长度是7吗?因为该错误意味着您正在尝试访问超过列表长度的项。
打印a以查看实际长度。
发布于 2015-12-10 16:13:41
谢谢你的时间和分析..。虽然当我发现错误到"/tmp/passwd“文件本身时,我得到了这个错误,因为最初的几行输出已经损坏,无法读取它。在重新检索一个正常工作的脚本后.
https://stackoverflow.com/questions/34204027
复制相似问题