I have data like this :data.txt
Product list
Name Quantity Price
Iphone11 5 14000000.0
SS note 10 4 13000000.0
Nokia C100 1 20000000.0
and this is my code to filter the
fname = open("Data.txt")
num_line = 0
for line in fname:
num_line += 1
if num_line == 1 or num_line == 2:
continue
data = line.strip().split()
if data == []:
continue
print(data)
And I have a result:
['Iphone11', '5', '14000000.0']
['SS', 'note', '10', '4', '13000000.0']
['Nokia', 'C100', '1', '20000000.0']
I want my code have format like it to put into my database:
['Iphone11', '5', '14000000.0']
['SS note 10', '4', '13000000.0']
['Nokia C100', '1', '20000000.0']
please help me
>Solution :
You can use re.sub and replace all space with one space. then use str.rsplit to split from the right and set maxsplit=2 for splitting only two times and skip from the other for each line. (It’s better to use with like below, otherwise, you need to close the file after opening and reading.)
import re
with open("Data.txt") as fname:
num_line = 0
for line in fname:
num_line += 1
if num_line == 1 or num_line == 2:
continue
line = re.sub(r'(\s+)', ' ', line)
data = line.strip().rsplit(sep=' ', maxsplit=2)
if data == []:
continue
print(data)
['Iphone11', '5', '14000000.0']
['SS note 10', '4', '13000000.0']
['Nokia C100', '1', '20000000.0']