Berecz Balázs
Berecz Balázs

Reputation: 153

Python file reding and splitting

file ="data.txt"
data=[]
with open(file) as i:
    data=i.readlines()    
for i in data:
        a=i.replace(".",";")
        a.split(";")
        newdata.append(a)
        print(a[1])

So if I know well data now is a list of strings, is it? I want to replace the . with ; and split it into a list of strings and save it.

example data.txt:

  1. grillsütő; jó állapotú; 5000
  2. gyerek bicikli; 14"-os; 10000

If I know well after the reading the data variable:

[1. grillsütő; jó állapotú; 5000] //0.index

[4. gyerek bicikli; 14"-os; 10000] //1.index

and what I want:

[[1][ grillsütő][ jó állapotú][ 5000]] //0.index

[[4][ gyerek bicikli][ 14"-os][ 10000]] //[1][1]:[ gyerek bicikli]

What am I missing?

Upvotes: 0

Views: 55

Answers (2)

shahaf
shahaf

Reputation: 4983

example snippet

str = "1;2;3;4"
parts = str.split(";")
final_array = [[e] for e in parts]
print final_array

output [['1'], ['2'], ['3'], ['4']]

Upvotes: 1

Austin
Austin

Reputation: 26037

You could do this way:

file = "data.txt" 
data, newdata = [], []
with open(file) as i: 
    data = i.readlines() 
for i in data:
    a = i.replace(".",";")
    newdata.append([[j] for j in a.split(";")])
print(newdata)

# [[['1'], [' grillsütő'], [' jó állapotú'], [' 5000']],   
#  [['4'], [' gyerek bicikli'], [' 14"-os'], [' 10000']]]   

If you wish to remove unnecessary spaces around the items in the list, you could do strip:

newdata.append([[j.strip()] for j in a.split(";")])

Upvotes: 1

Related Questions