Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split one file into two files using Python? [closed]

Tags:

python

file

split

I have a file containing some lines of code followed by a string pattern. I need to write everything before the line containing the string pattern in file one and everything after the string pattern in file two:

e.g. (file-content)

  • codeline 1
  • codeline 2
  • string pattern
  • codeline 3

The output should be file one with codeline 1, codeline 2 and file two with codeline 3.

I am familiar with writing files, but unfortunately I do not know how to determine the content before and after the string pattern.

like image 869
dom_frank Avatar asked Nov 28 '22 09:11

dom_frank


2 Answers

If the input file fits into memory, the easiest solution is to use str.partition():

with open("inputfile") as f:
    contents1, sentinel, contents2 = f.read().partition("Sentinel text\n")
with open("outputfile1", "w") as f:
    f.write(contents1)
with open("outputfile2", "w") as f:
    f.write(contents2)

This assumes that you know the exact text of the line separating the two parts.

like image 188
Sven Marnach Avatar answered Dec 04 '22 16:12

Sven Marnach


This approach is similar to Lev's but uses itertools because it's fun.

 dont_break = lambda l: l.strip() != 'string_pattern'

 with open('input') as source:
     with open('out_1', 'w') as out1:
         out1.writelines(itertools.takewhile(dont_break, source))
     with open('out_2', 'w') as out2:
         out2.writelines(source)

You could replace the dont_break function with a regular expression or anything else if necessary.

like image 21
Danica Avatar answered Dec 04 '22 16:12

Danica