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
  Read csv file through PyCharm kimx0961 3 112 Yesterday, 07:05 PM
Last Post: perfringo
  Accessing varying command line arguements Rakshan 3 148 Jul-28-2021, 03:18 PM
Last Post: snippsat
  Open and read multiple text files and match words kozaizsvemira 3 3,812 Jul-07-2021, 11:27 AM
Last Post: Larz60+
  Why it does not print(file.read()) Rejaul84 1 246 Jul-01-2021, 10:37 PM
Last Post: bowlofred
  How to capture string from a line to certain line jerald 1 238 Jun-30-2021, 05:13 PM
Last Post: Larz60+
  Read and write active Excel file euras 4 370 Jun-29-2021, 11:16 PM
Last Post: Pedroski55
  [Solved] Reading every nth line into a column from txt file Laplace12 7 478 Jun-29-2021, 09:17 AM
Last Post: Laplace12
  [solved] unexpected character after line continuation character paul18fr 4 318 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  [Solved] Trying to read specific lines from a file Laplace12 7 521 Jun-21-2021, 11:15 AM
Last Post: Laplace12
  Reading and storing a line of output from pexpect child eagerissac 0 174 Jun-17-2021, 12:22 PM
Last Post: eagerissac

Forum Jump:

User Panel Messages

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