Python Forum
How to read text file line by line - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to read text file line by line (/thread-22249.html)



How to read text file line by line - SriRajesh - Nov-05-2019

HI,
I have the below file (.config, which is similar to a text file), and I want to read and save it into dataframe.
I use the below code:



PO_UI{DC volt
Current IR
Density mass kg
}PO_UI
****************************
Type of cell 
Current mode
Voltage
*******************
I only want to catch data between "PO_UI{" and "}PO_UI"

when I use the below code, I am getting the different data type

0 PO_UI{DC volt
Name: 0, dtype: object
0 Current IR
Name: 1, dtype: object
0 Density mass kg
Name: 2, dtype: object
0 }PO_UI
Name: 3, dtype: object
0 ****************************
Name: 4, dtype: object
0 Type of cell
Name: 5, dtype: object


my desired output (in dataframe):


DC volt
Current IR
Density mass kg
import pandas as pd
with open("inputconfig.config") as f:
    content = f.readlines()
    content = [x.strip() for x in content] 
	

df = pd.DataFrame(content) 

for i in range(len(df)):
    tmp = df.iloc[i]
    print(tmp)



RE: How to read text file line by line - snippsat - Nov-05-2019

Parse clean up data first then load into dataframe,a common way is to use regex with this.
Example.
data = '''\
PO_UI{DC volt
Current IR
Density mass kg
}PO_UI
****************************
Type of cell
Current mode
Voltage
*******************'''
>>> import re 
>>> 
>>> r = re.findall(r"\{(.*)\}", data, re.DOTALL)
>>> r
['DC volt\nCurrent IR\nDensity mass kg\n']
>>> 
>>> print(''.join(r).strip())
DC volt
Current IR
Density mass kg