Search code examples
pythonfiletextdelimitercut

Python - Use Delimiter to Cut Off Output


The solution to the below may seem pretty "basic" to some of you; I've tried tons of source code and tons of reading to accomplish this task and constantly receive output that's barely readable to me, which simply doesn't execute, or just doesn't let me out of the loop.

I have tried using: split(), splitlines(), import re - re.sub(), replace(), etc.

But I have only been able to make them succeed using basic strings, but not when it has come to using text files, which have delimiters, involve new lines. I'm not perfectly sure how to use for loops to iterate through text files although I have used them in Python to create batch files which rely on increments. I am very confused about the current task.

=========================================================================

Problem:

I've created a text file (file.txt) that features the following info:

2847:784          3637354:
347263:9379       4648292:
63:38940          3547729:

I would like to use the first colon (:) as my delimiter and have my output print only the numbers that appear before it on each individual line. I want it to look like the following:

2847
347263
63

I've read several topics and have tried to play around with the coded solutions but have not received the output I've desired, nor do I think I fully understand what many of these solutions are saying. I've read several books and websites on the topic to no avail so what i am resorting to now is asking in order to retrieve code that may help me, then I will attempt to play around with it to form my own understanding. I hope that does not make anyone feel as though they are working too hard on my behalf. What I have tried so far is:

tt = open('file.txt', 'r').read()
[i for i in tt if ':' not in i]


vv = open('file.txt', 'r').read()
bb = vv.split(':')
print(bb)


vv = open('file.txt', 'r').read()
bb = vv.split(':')
for e in bb:
    print(e)


vv = open('file.txt', 'r').read()
bb = vv.split(':')
lines = [line.rstrip('\n') for line in bb]
print(lines)


io = open('file.txt', 'r').read()
for line in io.splitlines():
print(line.split(" ",1)[0]


with open('file.txt') as f:
lines = f.readlines()
print(lines)

The output from each of these doesn't give me what I desire, but I'm not sure what I'm doing wrong at all. Is there a source I can consult for guidance. I have been reading the forum along with, "Fluent Python," "Data Wrangling with Python," "Automate the Boring Stuff," and "Learn Python the Hard Way," and I have not been able to figure this problem out. Thanks in advance for the assistance.


Solution

  • Try this:

    with open('file.txt') as myfile:
        for line in myfile:
            print(line.split(':')[0])