如何使用Python将一个文件分成两个文件? [英] How do I split one file into two files using Python?

查看:245
本文介绍了如何使用Python将一个文件分成两个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些代码行和一个字符串模式的文件.我需要在文件1中包含字符串模式的行之前写入所有内容,在文件2中包含字符串模式的行之后写入所有内容:

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:

例如(文件内容)

  • 代码行1
  • 代码行2
  • 字符串模式
  • 代码行3

输出应该是带有代码行1的文件1和带有代码行3的文件2.

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.

推荐答案

如果输入文件适合内存,最简单的解决方案是使用str.partition():

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.

这篇关于如何使用Python将一个文件分成两个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆