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
  Βad Input on line 12 Azdaghost 5 1,325 Apr-19-2025, 10:22 PM
Last Post: Azdaghost
Question [SOLVED] [Beautiful Soup] Move line to top in HTML head? Winfried 0 309 Apr-13-2025, 05:50 AM
Last Post: Winfried
  Insert command line in script lif 4 1,039 Mar-24-2025, 10:30 PM
Last Post: lif
  Entry field random pull from list, each return own line Bear1981 6 849 Feb-25-2025, 06:09 AM
Last Post: Pedroski55
  How to revert back to a previous line from user input Sharkenn64u 2 1,038 Dec-28-2024, 08:02 AM
Last Post: Pedroski55
  How to read a file as binary or hex "string" so that I can do regex search? tatahuft 3 1,227 Dec-19-2024, 11:57 AM
Last Post: snippsat
  Read TXT file in Pandas and save to Parquet zinho 2 1,329 Sep-15-2024, 06:14 PM
Last Post: zinho
  Pandas - error when running Pycharm, but works on cmd line zxcv101 2 2,479 Sep-09-2024, 08:03 AM
Last Post: pinkang
  Simplest way to run external command line app with parameters? Winfried 2 1,335 Aug-19-2024, 03:11 PM
Last Post: snippsat
  Pycharm can't read file Genericgamemaker 5 1,665 Jul-24-2024, 08:10 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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