Python Forum
How to read text file line by line
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to read text file line by line
#1
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)
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to do line continuation in Jupyter Notebook? Mark17 4 145 Sep-22-2021, 04:22 PM
Last Post: ibreeden
  append a string to a modified line Mr_Blue 10 379 Sep-16-2021, 07:24 PM
Last Post: Mr_Blue
Lightbulb Multiple inputs on the same line (beginner) dementshuk 9 340 Sep-03-2021, 02:21 PM
Last Post: dementshuk
  Line 42 syntax error..Help!!1 patpython 4 275 Sep-01-2021, 03:22 PM
Last Post: deanhystad
  [SOLVED] Why does regex fail cleaning line? Winfried 5 478 Aug-22-2021, 06:59 PM
Last Post: Winfried
  Presenting multiline data into single line aaronbuhu 1 268 Aug-05-2021, 10:57 AM
Last Post: jamesaarr
  Read csv file through PyCharm kimx0961 3 418 Aug-01-2021, 07:05 PM
Last Post: perfringo
  Accessing varying command line arguements Rakshan 3 301 Jul-28-2021, 03:18 PM
Last Post: snippsat
  Open and read multiple text files and match words kozaizsvemira 3 4,126 Jul-07-2021, 11:27 AM
Last Post: Larz60+
  Why it does not print(file.read()) Rejaul84 1 393 Jul-01-2021, 10:37 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020