所以我需要在python中拆分列表,我的txt文件如下所示:
ip,user,password
ip,user,passord
等等。我已经在列表中读过了,我可以拆分它,但我只会得到第一个ip。我希望能够将列表分成三个单独的列表,一个用于ip,用户和密码。到目前为止,这是我的代码:
def OpenFile():
read = [line.strip() for line in open("People.txt" , 'r')
return read
jh = OpenFile()
sp = [i.split(',',1)[0] for i in jh]
答案 0 :(得分:3)
您可以按,
拆分它们,然后将zip
拆分列表拆分为
with open("People.txt" , 'r') as inFile:
ips, users, passwords = zip(*[line.strip().split(",") for line in inFile])
现在,如果您打印变量,您将获得
print ips, users, passwords
('ip', 'ip') ('user', 'user') ('password', 'passord')
答案 1 :(得分:2)
使用zip
:
>>> lines = ['ip,user,password', 'ip,user,passord']
>>> rows = [line.strip().split(',') for line in lines] # `lines` -> file object
>>> rows
[['ip', 'user', 'password'], ['ip', 'user', 'passord']]
>>> zip(*rows) # Output will be different in Python 3.x
[('ip', 'ip'), ('user', 'user'), ('password', 'passord')]
>>> ip, user, password = zip(*rows)
>>> ip
('ip', 'ip')
>>> user
('user', 'user')
>>> password
('password', 'passord')