Home > Back-end >  Read just some Lines from TXT file and save them to CSV
Read just some Lines from TXT file and save them to CSV

Time:10-03

im trying to make my task simplier. I have a lots of TXT files, with orders from our shops, whitch looks like this, example of TXT file

.

I need only NAME and TELEPHONE from this file. Each order has two empty lines between the next order. The name is the second line and the telephone is the seventh line in each order. I need these 2 variables(telephone,name). Select from the txt file and write them into the CSV file used by google contacts. GOOGLE CSV Contacts My question is there some simple code or program whitch can help me ? Thanks for answears.

CodePudding user response:

You should be able to use the built in functions in python to read from the TXT file.

https://www.pythontutorial.net/python-basics/python-read-text-file/

Then use openpyxl to write to CSV.

Hope this helps!

CodePudding user response:

#! /usr/bin/python

import re

tel_num=re.compile(r"(\ \d{1,2})?[\s.-]?\d{3}[\s.-]?\d{4}")
phone=[]
linenum=0

with open ('file.txt', 'rt') as fil:
    for line in fil:
        if tel_num.search(line)!=None:
            phone.append((linenum,line.rstrip('\n')))

for p in phone:
    print(f"Contact Number: {str(phone[p])}")
  • Related