Paresh Lohakare
Paresh Lohakare

Reputation: 1

Python: line split and join

I have a file with contents in following format:

a1 b1 c1 d1|e1|f1|path/file_name/n

a2 b2 c2 d2|e2|f2|path/file_name/n

In the above string, file names can have space and thus the above one can change to:

a b c d|e|f|path/file name.txt

I need to iterate through each line in a file to search the records containing file name. and while searching, I need to match with certain contents in a given line for e.g. if a > x and e = 'test' etc.. as part of the search.

To begin, I tried, below:

for line in data_file:
    f_a f_b f_c f_d = line.split(' ')

Above works fine if file name doesn't have spaces and if it has space, then error out as 'too many values to unpack'.(expected 4) If I use,

f_a f_b f_c f_d = line.rsplit(' ', 3)

then it does not store the file with name after 1st space.

Can anyone please suggest solution to this problem.

Upvotes: 0

Views: 302

Answers (1)

Antimony
Antimony

Reputation: 2240

If it is true that in all rows the filename is the string after the last '|', then try splitting with that first.

Using a b c d|e|f|path/file name.txt as the example, first do

f_list, f_e, f_f, filename = line.split('|')

This gets you the path + filename in filename whether it has a space or not. Then you can split f_list further the way you are currently doing:

f_a, f_b, f_c, f_d = f_list.split(' ')

Upvotes: 1

Related Questions