Des
Des

Reputation: 11

How to split lines in python

I am looking for a simple way to split lines in python from a .txt file and then just read out the names and compare them to another file.

I've had a code that split the lines successfully, but I couldn't find a way to read out just the names, unfortunately the code that split it successfully was lost.

this is what the .txt file looks like.

Id;Name;Job;
1;James;IT;
2;Adam;Director;
3;Clare;Assisiant;

example if the code I currently have (doesn't output anything)

my_file = open("HP_liki.txt","r")
flag = index = 0 
x1=""
for line in my_file: 
    line.strip().split('\n') 
    index+=1 
content = my_file.read()
list=[]
lines_to_read = [index-1]
for position, line1 in enumerate(x1):
    if position in lines_to_read:
        list=line1
        x1=list.split(";")
    print(x1[1])

I need a solution that doesn't import pandas or csv.

Upvotes: 1

Views: 4379

Answers (3)

darth vader
darth vader

Reputation: 578

So without using any external library you can use simple file io and then generalize according to your need.

readfile.py

file = open('datafile.txt','r')

for line in file:
    line_split = line.split(';')
    if (line_split[0].isdigit()):
        print(line_split[1])

file.close()

datafile.txt

Id;Name;Job;
1;James;IT;
2;Adam;Director;
3;Clare;Assisiant;

If you run this you'll have output

James
Adam
Clare

You can change the if condition according to your need

Upvotes: 1

Prune
Prune

Reputation: 77827

The first part of your code confuses me as to your purpose.

for line in my_file: 
    line.strip().split('\n') 
    index+=1 
content = my_file.read()

Your for loop iterates through the file and strips each line. Then it splits on a newline, which cannot exist at this point. The for already iterates by lines, so there is no newline in any line in this loop.

In addition, once you've stripped the line, you ignore the result, increment index, and leave the loop. As a result, all this loop accomplishes is to count the lines in the file.

The line after the loop reads from a file that has no more data, so it will simply handle the EOF exception and return nothing.


If you want the names from the file, then use the built-in file read to iterate through the file, split each line, and extract the second field:

name_list = [line.split(';')[1]
               for line in open("HP_liki.txt","r") ]

name_list also includes the header "Name", which you can easily delete.

Does that handle your problem?

Upvotes: 1

JenilDave
JenilDave

Reputation: 604

I have my dataf.txt file:

Id;Name;Job;
1;James;IT;
2;Adam;Director;
3;Clare;Assisiant;

I have written this to extract information:

with open('dataf.txt','r') as fl:
    data = fl.readlines()
    a = [i.replace('\n','').split(';')[:-1] for i in data]
    print(a[1:])

Outputs:

[['1', 'James', 'IT'], ['2', 'Adam', 'Director'], ['3', 'Clare', 'Assisiant']]

Upvotes: 0

Related Questions