Python Forum
[split] Splitting a string into six pieces
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[split] Splitting a string into six pieces
#1
Hi,
I am trying to read data from a text file and split it into six parts.
I the code is not able to perform intended function for reasons unidentified.Please help.

The text file has below data:

Data_Val5 12/25/2018 15:15 406 1 43459635537
Data_Val6 12/25/2018 15:15 379 1 43459635537
Data_Val7 12/25/2018 15:15 352 1 43459635537
Data_Val8 12/25/2018 15:15 325 1 43459635537
Data_Val9 12/25/2018 15:15 298 1 43459635537
Data_Val10 12/25/2018 15:15 270 1 43459635537
Data_Val1 12/25/2018 15:15 514 1 43459635537



The code is as below:
#open file
dataFile = open('C:\\Users\\USER1\\Desktop\\PyWork\\DataFile_1.txt')

for dataStr in dataFile:
    (d1,d2,d3,d4,d5,d6)=dataStr.split()#split data into six parts.

#close file
dataFile.close()
The output is as below:
Output:
"C:\Users\USER1\Google Drive\Books\Python\Task\TASK1\venv\Scripts\python.exe" "C:/Users/USER1/Google Drive/Books/Python/Task/TASK1/KTP700_Logfile_Mgr.py" Traceback (most recent call last): File "C:/Users/USER1/Google Drive/Books/Python/Task/TASK1/KTP700_Logfile_Mgr.py", line 6, in <module> (d1,d2,d3,d4,d5,d6)=dataStr.split() ValueError: not enough values to unpack (expected 6, got 1) Process finished with exit code 1
Reply
#2
Does your file have any blank lines in it? That could cause the problem. You can be preemptive about it with a conditional:

for dataStr in dataFile:
    if dataStr.strip():
        (d1,d2,d3,d4,d5,d6)=dataStr.split()#split data into six parts.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split string into 160-character chunks while adding text to each part iambobbiekings 9 9,583 Jan-27-2021, 08:15 AM
Last Post: iambobbiekings
  Split String lekuru01 6 3,474 Mar-19-2019, 10:42 AM
Last Post: lekuru01
  Using a function: splitting, joining, and slicing a string Drone4four 2 4,832 Dec-27-2018, 07:52 AM
Last Post: perfringo
  Quickest way of splitting a string yanhto 1 2,450 May-01-2018, 12:24 PM
Last Post: snippsat
  How to access each line in for loop and split string SriRajesh 2 3,132 Aug-14-2017, 06:05 PM
Last Post: tetrmnot
  [split] deleting pieces of strings viking_helgi 2 3,446 Feb-04-2017, 02:15 PM
Last Post: Ofnuts
  Splitting A String In Python Saif133 6 6,360 Jan-14-2017, 04:09 AM
Last Post: Saif133

Forum Jump:

User Panel Messages

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