如何在Python中打开/ etc / group时只显示用户的名字?

问题描述 投票:-1回答:2

这是我的代码:

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:”的用户名

python list grep
2个回答
0
投票

你几乎达到了目标。通过对代码的一点修复,这是解决方案。

 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('%s\n' % u)
            print u

0
投票

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

with open("/etc/group" , "r") as f2:
   for line in f2:
       list1=line.split(str=":")
       print list1[0]
© www.soinside.com 2019 - 2024. All rights reserved.