Reputation:
Based on this example of a line from a file
1:alpha:beta
I'm trying to get python to read the file in and then line by line print whats after the 2nd ':'
import fileinput
#input file
x = fileinput.input('ids.txt')
strip_char = ":"
for line in x:
strip_char.join(line.split(strip_char)[2:])
This produces no results, however from a console session on a single line it works fine
Python 2.7.3rc2 (default, Apr 22 2012, 22:35:38)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
data = '1:alpha:beta'
strip_char = ":"
strip_char.join(data.split(strip_char)[2:])
'beta'
What am i doing wrong please? Thanks
Upvotes: 1
Views: 161
Reputation: 143047
For the data format given this will work:
with open('data.txt') as inf:
for line in inf:
line = line.strip()
line = line.split(':')
print ':'.join(line[2:])
For '1:alpha:beta'
the output would be 'beta'
For '1:alpha:beta:gamma'
the output would be 'beta:gamma'
(Thanks for @JAB pointing this out)
Upvotes: 1
Reputation: 501
You get just 'beta' because join gives you a string:
data = '1:alpha:beta'
strip_char = ":"
strip_char.join(data.split(strip_char)[2:])
'beta'
Try this:
lines=[]
with open('filePath', 'r') as f:
for line in f.readlines():
lines.append(line.strip())
for line in lines: print line.split(':')[1:]
Upvotes: 0
Reputation: 21079
Values returned by functions aren't automatically sent to stdout in non-interactive mode, you have to explicitly print them.
So, for Python 2, use print line.split(strip_char, 2)[2]
. If you ever use Python 3, it'll be print(line.split(strip_char, 2)[2])
.
(Props to Jon Clements, I forgot you could limit how many times a string will be split.)
Upvotes: 1
Reputation: 142116
If it's everything after the 2nd ':' as a string (which can include ':') then use the maxsplit option, eg:
line.split(':', 2)[2]
eg:
>>> d = '1:alpha:beta:charlie:delta'
>>> d.split(':', 2)
['1', 'alpha', 'beta:charlie:delta']
This saves joining afterwards
Upvotes: 1