Welcome, guest | Sign In | My Account | Store | Cart

Converts a CSV file to a flat file (table).

Python, 42 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# CSV to Flat-file Converter
# FB - 20150802
import sys

delimiterInputFile = "," # ";" "|"
delimiterOutputFile = " " # "" "," ";" "|"

if len(sys.argv) != 3:
    print "USAGE:"
    print "[python] CSV2FlatFile.py InputFile OutputFile"
    sys.exit()

inputFileName = sys.argv[1]
outputFileName = sys.argv[2]

inputFile = open(inputFileName, "r")
inputFileLines = inputFile.readlines()
inputFile.close()
if len(inputFileLines) == 0:
    print "No input data!"
    sys.exit()
# strip EOL
for j, inputFileLine in enumerate(inputFileLines):
    inputFileLines[j] = inputFileLines[j].strip()

numColumns = len(inputFileLines[0].split(delimiterInputFile))
maxColumnLengths = [0 for i in range(numColumns)]
# find max length for each column
for inputFileLine in inputFileLines:
    inputFileLineList = inputFileLine.split(delimiterInputFile)
    for i in range(numColumns):
        if len(inputFileLineList[i]) > maxColumnLengths[i]:
            maxColumnLengths[i] = len(inputFileLineList[i])
    
outputFile = open(outputFileName, "w")
for inputFileLine in inputFileLines:
    inputFileLineList = inputFileLine.split(delimiterInputFile)
    for i in range(numColumns):
        inputFileLineList[i] = inputFileLineList[i].ljust(maxColumnLengths[i])
    outputFileLine = delimiterOutputFile.join(inputFileLineList)
    outputFile.write(outputFileLine + "\n")
outputFile.close()
Created by FB36 on Sun, 2 Aug 2015 (MIT)
Python recipes (4591)
FB36's recipes (148)

Required Modules

  • (none specified)

Other Information and Tasks