HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Optimize a simple and quick python script for transposing a .csv file

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scriptsimpletransposingfilecsvpythonoptimizequickandfor

Problem

I need to transpose the following file output1.csv, which is is a result from a quantum chemistry calculation into a single colum efficiently:

```
Frequencies -- 18.8210 44.7624 46.9673
Frequencies -- 66.6706 102.0432 112.4930
Frequencies -- 124.4601 138.4393 180.1404
Frequencies -- 230.0306 240.4389 258.2459
Frequencies -- 282.7781 340.8302 357.7789
Frequencies -- 378.9043 384.1284 401.4285
Frequencies -- 418.0523 444.2264 447.6885
Frequencies -- 473.2391 501.0937 518.9083
Frequencies -- 559.5925 609.9256 623.7729
Frequencies -- 657.4144 672.5480 728.2009
Frequencies -- 740.5035 750.3238 757.2199
Frequencies -- 774.6343 806.7750 815.9990
Frequencies -- 839.3050 858.0716 876.1641
Frequencies -- 888.6654 942.2963 965.7888
Frequencies -- 987.3819 994.7388 1020.8724
Frequencies -- 1025.0426 1045.5129 1059.0966
Frequencies -- 1076.5127 1143.1178 1155.4200
Frequencies -- 1208.6790 1219.7513 1244.7080
Frequencies -- 1265.6108 1287.8830 1300.0463
Frequencies -- 1325.0427 1339.0678 1353.0061
Frequencies -- 1369.0614 1408.5258 1433.0543
Frequencies -- 1452.4148 1454.6319 1500.4304
Frequencies -- 1511.2305 1517.2562 1552.9189
Frequencies -- 1560.5313 1636.2290 1640.1732
Frequencies -- 1664.8747 1681.5566 1703.2026
Frequencies -- 1770.2627

Solution

I believe there is a much simpler way of doing this.

If I correctly understand the problem, the idea is to produce a single column of frequencies.

with open('input.txt', 'r') as infile, open('out.csv', 'w') as outfile:
    print >> outfile, "Frequency"
    for line in infile:
        for freq in line.split()[2:]:
            print >> outfile, freq


This iterates over each line in the input file. It uses split to eliminate whitespace and to split each line into fields. It then discards the first two, which are assumed to be "Frequencies" and "--" and writes the remaining fields to the output file.

Code Snippets

with open('input.txt', 'r') as infile, open('out.csv', 'w') as outfile:
    print >> outfile, "Frequency"
    for line in infile:
        for freq in line.split()[2:]:
            print >> outfile, freq

Context

StackExchange Code Review Q#134045, answer score: 2

Revisions (0)

No revisions yet.