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 add multi-line comment section? Winfried 1 137 Mar-24-2024, 04:34 PM
Last Post: deanhystad
  break print_format lengthy line akbarza 4 273 Mar-13-2024, 08:35 AM
Last Post: akbarza
  Reading and storing a line of output from pexpect child eagerissac 1 4,144 Feb-20-2024, 05:51 AM
Last Post: ayoshittu
  coma separator is printed on a new line for some reason tester_V 4 417 Feb-02-2024, 06:06 PM
Last Post: tester_V
  problem with spliting line in print akbarza 3 335 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  Unable to understand the meaning of the line of code. jahuja73 0 268 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  Receive Input on Same Line? johnywhy 8 607 Jan-16-2024, 03:45 AM
Last Post: johnywhy
  Recommended way to read/create PDF file? Winfried 3 2,783 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,308 Nov-09-2023, 10:56 AM
Last Post: mg24
  Reading in of line not working? garynewport 2 784 Sep-19-2023, 02:22 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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