user8018985
user8018985

Reputation:

While trying to copy data Next to variables from text to csv with python getting error:

I am trying to copy values of data seprated with: from text file. Text file having data like in this form:

I have 50+ text file contains data in this form:

Type: Assume 
Number: 123456
Name: Assume
Phone Number: 000-000
Email Address: [email protected]
Mailing Address: Assume

i am trying to get data values in this format in csv from multiple text files:

Type     Number  Name     Phone      email         Mailing Address
Assume   123456  Assume   000-000   [email protected]  Assume

Here is the code:

import re
import csv

file_h = open("out.csv","a")
csv_writer = csv.writer(file_h)



def writeHeading(file_content):
    list_of_headings = []
    for row in file_content:
        key = str(row.split(":")[0]).strip()
        list_of_headings.append(key)

    csv_writer.writerow(tuple(list_of_headings))

def writeContents(file_content):
    list_of_data = ['Number']
    for row in file_content:
        value = str(row.split(":")[1]).strip()
        list_of_data.append(value)
    csv_writer.writerow(tuple(list_of_data))

def convert_txt_csv(filename):
    file_content = open(filename,"r").readlines()
    return file_content

list_of_files = ["10002.txt","10003.txt","10004.txt"]

# for writing heading once
file_content = convert_txt_csv(list_of_files[0])
writeHeading(file_content)

# for writing contents
for file in list_of_files:
    file_content = convert_txt_csv(file)
    writeContents(file_content)

file_h.close()

Here is the following error:

Traceback (most recent call last):
  File "Magnet.py", line 37, in <module>
    writeContents(file_content)
  File "Magnet.py", line 20, in writeContents
    value = str(row.split(":")[1]).strip()
IndexError: list index out of range

Upvotes: 0

Views: 32

Answers (1)

zwer
zwer

Reputation: 25799

Your code probably encounters a blank line at the end of the first file, or any line that doesn't have a : in it, so when you try to split it into key/values it complains as it didn't get a list of expected length. You can fix that easily by checking if there is a colon on the current line, i.e.:

for row in file_content:
    if ":" not in row:  # or you can do the split and check len() of the result
        continue
    key = row.split(":")[0].strip()
    list_of_headings.append(key)

But... While the task you're attempting looks extremely simple, keep in mind that your approach assumes that all the files are equal, with equal number key: value combinations and in the same order.

You'd be much better off by storing your parsed data in a dict and then using csv.DictWriter() to do your bidding.

Upvotes: 1

Related Questions