如何在 Python 中打开 /etc/group 时仅显示用户的名称



这是我的代码:

grouplist = open("/etc/group" , "r")
with grouplist as f2:
    with open("group" , "w+") as f1:
    f1.write(f2.read())
    f1.seek(0,0)
    command = f1.read()
    print
    print command

我可以使用什么命令使其仅显示用户的名称而不显示":x:1000:"

你几乎达到了目标。在代码中进行一些修复后,这是解决方案。

 with open("/etc/group" , "r") as source:
    with open("./group" , "w+") as destination:
        destination.write(source.read())
        source.seek(0,0)
        for user in source.readlines():
            print user[: user.index(':')]

但是,这仅显示名称,但仍复制原始文件。

这样,您只写入新文件中的名称。

with open("/etc/group" , "r") as source:
    with open("./group" , "w+") as destination:
        for user in source.readlines():
            u = user[: user.index(':')]
            destination.write('%sn' % u)
            print u

怎么样split() [1] [2]

with open("/etc/group" , "r") as f2:
   for line in f2:
       list1=line.split(str=":")
       print list1[0]

最新更新