Fangqi Chen
Fangqi Chen

Reputation: 1

Split a text file into multiple text files based on a certain criteria

The text file comes in this format:

[email protected] | Country: US [email protected] | Country: CA

I want to be able to split them into multiple files based on their countries, like US.txt and CA.txt

Upvotes: 0

Views: 89

Answers (1)

jhill515
jhill515

Reputation: 943

I'm noticing that the pattern you have above seems to be a single-line file in the pattern of:

_email_ | Country: _NNN_

This can be a bit tricky to parse because what seems like a delineater really is not. One bit of steering direction I'll offer is this:

  • Read the whole line first
  • split() with ' '; You will wind up with a list with a pattern of [email, '|', 'Country:' NNN] that repeats over and over again.
  • Take each sub-pattern and look at the fourth element (lets call this natStr)
  • Open a file for appending named natstr + '.txt' and write that sub-pattern (recombining it)

I purposefully did not include an actual Python implementation because you should take a look at the split() string function and understand file I/O in Python.

Upvotes: 1

Related Questions