首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带导入模块的Python IndexError

带导入模块的Python IndexError
EN

Stack Overflow用户
提问于 2015-12-10 14:09:49
回答 2查看 171关注 0票数 0

下面的脚本在pyhthon 2.7上运行得很好,

代码语言:javascript
复制
#!/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,加入

请帮帮我,我是初学者。

EN

回答 2

Stack Overflow用户

发布于 2015-12-10 14:19:59

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

打印a以查看实际长度。

票数 0
EN

Stack Overflow用户

发布于 2015-12-10 16:13:41

谢谢你的时间和分析..。虽然当我发现错误到"/tmp/passwd“文件本身时,我得到了这个错误,因为最初的几行输出已经损坏,无法读取它。在重新检索一个正常工作的脚本后.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34204027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档