Jasper StaTham
Jasper StaTham

Reputation: 117

Python regarding .split in file

Hello can anyone please help out with this?

this is the content of my txt file

DICT1 Assignment 1 25 100 nothing anyway at all
DICT2 Assignment 2 25 100 nothing at all
DICT3 Assignment 3 50 100 not at all

this is my code

from pathlib import Path
home = str(Path.home())

with open(home + "\\Desktop\\PADS Assignment\\DICT1 Assessment Task.txt", "r") as r:
    for line in r:
       print(line.strip().split())

my output of the code is

['DICT1', 'Assignment', '1', '25', '100', 'nothing']
['DICT2', 'Assignment', '2', '25', '100', 'nothing', 'at', 'all']
['DICT3', 'Assignment', '3', '50', '100', 'not', 'at', 'all']

Now my question is , how do i make the output to be

['DICT1', 'Assignment 1', '25', '100', 'nothing']
['DICT2', 'Assignment 2', '25', '100', 'nothing at all']
['DICT3', 'Assignment 3', '50', '100', 'not at all']

Upvotes: 0

Views: 70

Answers (2)

mic4ael
mic4ael

Reputation: 8300

You could use the maxsplit parameter of the split method

line.split(maxsplit=5)

Of course if the format of the lines in your file is similar and you are using python 3.

For Python 2.x you should use

line.split(' ', 5)

Upvotes: 5

aveuiller
aveuiller

Reputation: 1551

Your main problem here is your input file, the separator in this file is a space but you also have some values with spaces to retrieve.

So you have two choices here:

  1. You either change the input file to be comma separated values, i.e.:

    DICT1, Assignment, 1, 25, 100, nothing anyway at all
    DICT2, Assignment, 2, 25, 100, nothing at all
    DICT3, Assignment, 3, 50, 100, not at all
    
  2. You change your script to unpack manually the end of lines once you got every other items:

    from pathlib import Path
    home = str(Path.home())
    
    with open(home + "\\Desktop\\PADS Assignment\\DICT1 Assessment Task.txt", "r") as r:
        for line in r:
            splittedLine = line.strip().split(" ")
            taskId = splittedLine[0]
            taskTitle = splittedLine[1]
            weight = splittedLine[2]
            fullMark = splittedLine[3]
            description = " ".join(splittedLine[4:])
    
            print("taskId: " + taskId + " - taskTitle: " + taskTitle + " - weight: " + weight + " -fullMark: " + fullMark + " - description: " +            description)
    

Upvotes: 2

Related Questions