【问题标题】:splitting a file into multiple files with a key word using python使用python将一个文件拆分为多个文件,其中包含一个关键字
【发布时间】:2018-09-27 22:04:43
【问题描述】:

我在 python 中有一个大文本文件。我想使用关键字将其拆分为 2。必须将关键字上方的文件复制到一个文件中,并将文件的其余部分复制到另一个文件中。我想将这些具有不同扩展名的文件保存在同一目录中。请帮我解决这个问题。

另外,如何将文件从一种格式转换为另一种格式? 例如,.txt 转 .xml 或 .cite 转 .xml?

【问题讨论】:

  • 您好,请编辑您的问题以分享您已经尝试过的任何代码,以及您对此所做的任何没有帮助的研究。
  • 谷歌文件管理。此外,考虑将整个文件加载为文本并使用 text.split(keyword) - 这会将其拆分为 2 个字符串,您可以将它们保存为不同的文件。

标签: python file split


【解决方案1】:

要回答您问题的第一部分,您可以在阅读文本后简单地使用split 函数并将它们写入您的新文件:

with open('oldfile.txt', 'r') as fh:
    text_split = fh.read().split(keyword)

with open('newfile' + extension1, 'w') as fh:
    fh.write(text_split[0])

with open('newfile' + extension2, 'w') as fh:
    # If you know that the keyword only appears once
    # you can changes this to fh.write(text_split[1])
    fh.write(keyword.join(text_split[1:]))

您问题的第二部分要困难得多。我不知道您使用的是哪种文件格式,但 txt 文件只是没有特定结构的纯文本。 XML 文件不能从任意格式转换。如果您使用 .txt 格式的 XML 文件,您可以简单地将格式更改为 XML,但如果您希望转换 CSV 等格式,我建议您使用 lxml 之类的库。

编辑:如果文件不适合内存,那么您可以遍历这些行:

with open('oldfile.txt', 'r') as fh:
    fh_new = open('newfile' + extension1, 'w')
    keyword_found = False
    line = fh.readline()
    while line:
        if not keyword_found:
            text_split = line.split(keyword)
            fh_new.write(text_split[0])
            if len(text_split) > 1: 
                fh_new.close()
                keyword_found = True
                fh_new = open('newfile' + extension2, 'w')
                fh_new.write(text_split[1:])
        else:
            fh_new.write(line)

        line = fh.readline()
    fh_new.close()

【讨论】:

  • 您拆分文件的解决方案对于大到无法一次全部放入内存的文件来说是个坏主意。他说他有一个大文件。
  • @kamyarhaqqani 如果您对有效的解决方案有任何建议,请告诉我。那真的很有帮助。谢谢大佬!
  • @Bharath kumar k 我已经发布了答案。
  • 如果您的文件不适合内存,我已经用解决方案更新了答案
【解决方案2】:

关于拆分文件,应该这样做(考虑到文件的大小):

import mmap
regex=b'your keyword'
f=open('your_path_to_the_main_file','rb')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
first_occurance_position=s.find(regex)
if(first_occurance_position==0)
 print('this is a mistake')
 f.close()
 quit()

buf_size=0xfff
first_part_file=open('your_path_to_the_first_part'+'.its_extension','wb')
second_part_file=open('your_path_to_the_second_part'+'.its_extension','wb')
i=0;
if(buf_size>len(regex)):
 buf_size=len(regex)
b=f.read(buf_size)
while(b):
 i=i+buf_size
 first_part_file.write(b)
 if(i==first_occurance_position):
  break
 if(first_occurance_position-i<buf_size):
  buf_size=first_occurance_position-i
 b=f.read(buf_size)

b=f.read(0xffff)
while(b):
 second_part_file.write(b)
 b=f.read(0xffff)

first_part_file.close()
second_part_file.close()
f.close()

【讨论】:

  • 感谢您的回答。它与复制每一行直到我们得到关键字然后将其余部分复制到其他文件有什么不同?我可以知道它的效率吗?
  • 您没有要求比您提到的更有效的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 2015-05-29
  • 2016-07-26
  • 1970-01-01
相关资源
最近更新 更多