I wish to perform the following task on the data.txt in my python script
read line by line data.txt
Once you read the first line split it using delimiter ":" i.e "user1" "psw1" & "Moni,Admi"
split the 3rd string i.e "Moni,Admi" using delimiter ","
same process for lines 2,3...etc
Below is what i tried but it is incorrect:
f = open("data.txt", "r")
for line in f.readlines():
etake = line.partition(":")
print "Hello"
print(etake[0])
for entry in etake:
print entry[0]
print entry[1]
words = entry[2].split(,)
for word in words:
print word
I tried to change etake = line.partition(":") with etake = line.split(":") but it still fails.
Last login: Wed Sep 21 18:05:57 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("str_test.py")
user1 psw1 Moni Admi
user2 psw2 Depl Moni Admi
>>> _
Well the reqirements here are nothing like your OP!
I noticed that you edited your post what was the edit???
Try this; it CAN be slimmed down. I will let you do that...
# python 2.7.x
f=open("/Users/barrywalker/data.txt", "r")
for line in f.readlines():
lst=line.split(":")
username=lst[0]
password=lst[1]
groups=lst[2]
print "Username=%s" %(username)
print "Password=%s" %(password)
print "Groups=%s" %(groups)
f.close()
Results:-
Last login: Wed Sep 21 20:14:55 on ttys000
AMIGA:barrywalker~> cd Desktop/Code/Python
AMIGA:barrywalker~/Desktop/Code/Python> python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("lst_test.py")
Username=user1
Password=psw1
Groups=Moni,Admi
Username=user2
Password=psw2
Groups=Depl,Moni,Admi
>>> exit()
AMIGA:barrywalker~/Desktop/Code/Python> _
IMPORTANT NOTE:-
you will be re-using the same variables per line loop!
You will have to intercept each loop to do something with the variables, that is up to you.