How do I split one file into two files using Pytho

2020-04-10 01:05发布

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.

7条回答
男人必须洒脱
2楼-- · 2020-04-10 01:39

A naive example (that doesn't load the file into memory like Sven's):

with open('file', 'r') as r:
    with open('file1', 'w') as f:
        for line in r:
            if line == 'string pattern\n':
                break
            f.write(line)
    with open('file2', 'w') as f:
        for line in r:
            f.write(line)

This assumes that 'string pattern' occurs once in the input file.

If the pattern isn't a fixed string, you can use the re module.

查看更多
登录 后发表回答