art_cs
art_cs

Reputation: 791

how to read each lines of a text file and convert each line to a tuple?

I try to read a text file line by line and convert each line to tuple . this is my text file data

danial feldroy - two scoops of django

james - python for everyone

I need to read and convert each line to a tuple like this ("danial feldroy "," two scoops of django") ("james "," python for everyone")

and I have to add this tuples to a list

nt = open('my_file.txt').readlines()
names_title = []
for book in nt:
    a = book.replace('-',',')
    convert_to_tuple = tuple(a)
    print(a)
    #but i have to remove the white spaces as well

result :

danial feldroy , two scoops of django

I expect this

danial feldroy,two scoops of django
    

then I want to change each lines to a tuple

("danial feldroy","two scoops of django")

but whenever I use tuple() it doesn't work as I expected ?

and the output for tuples

('d','a','n','i','a','l' etc ..

I expected this ("danial feldroy","two scoops of django")!

Upvotes: 0

Views: 1796

Answers (1)

adir abargil
adir abargil

Reputation: 5745

Did you try change what inside the loop to :

 nt = open('my_file.txt').readlines()
 names_title = []
 for book in nt:
     data_tuple = (x.strip() for x in book.split('-'))
     print(data_tuple)

The problem is you are trying to cast strings to tuples which is iterable and will cast each char to a specific character of the string. Instead using split() you will divide the parts you want by some character

Upvotes: 1

Related Questions