Python Forum

Full Version: How to access each line in for loop and split string
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to read text file and write csv: 
I use the following code,
import glob
import os
import re
list_of_files = glob.glob('D:\Mekala_Backupdata\PythonCodes/textFile.txt')
for fileName in list_of_files:
    fin = open(fileName, "r")
    data_list = fin.readlines()
    fin.close()
    targetSubString = '-------'
    indices = [idx for idx, s in enumerate(data_list) if targetSubString in s]
    reqData = data_list[indices[0] + 1:indices[1]]
    fout = open("stripD.csv", "w")
    fout.writelines(reqData)
    fout.flush()
    fout.close
1. I want to split the string in each line, and save first column into para_list, column3 into end_Value
2. in end_values, I want to keep the first string (if number, or logical operator), or whole siring if it is text.

My desired output:
Output:
    para_list:     parq     10Lqr     29Hyt     Zgeat1     Beget          end_values:     33.0 mm      23.0     1.0     Noraml set     12
please any one help, many thanks in advance,
my text file is below:    
Output:
    File Name:thUIK003K          Version:002BA07Gh     Name:HUJKO               Parameter        Start        End     -------------------------------------     parq             56 mm        33.0 mm      10Lqr            12.0 mm      23.0 mm     29Hyt            0.0 %        1.0 %     Zgeat1           normal set   noraml set     Beget            12 km        12 km     -------------------------------------     other events:     11000 vent trig     213455 alram          xpara  ypara     1      3     2      3     4      8     6      10     -------------------------------------
The split method will split those lines into three parts. Then you can abstract those parts with list comprehensions:

reqCols = [line.split() for line in reqData]
para_list = [line[0] for line in reqCols]
end_values = [line[2] for line in reqCols]
That will give you two lists with the lines you want to output.
Great, that is what i was looking for!