【问题标题】:Merging text files and delete file when you are done完成后合并文本文件和删除文件
【发布时间】:2014-08-04 23:42:15
【问题描述】:

我正在将一堆文本文件合并到“merged.txt”中。然后我使用collections.counter来统计merged.txt中所有单词的个数。我想知道在我拥有 mydict 之后是否有办法删除文件merged.txt。或者真的只是一种方法,让我在代码执行后没有merged.txt在我的目录中?

file_list = [file1, file2, ... file1000]
    with open(directory + '/' + i +'/merged.txt', 'w') as outfile:
        for fname in file_list:
            with open(fname) as infile:
                for line in infile:
                    outfile.write(line)

    words = re.findall(r'\w+', open(directory + '/' + i + '/merged.txt').read().lower())
    mydict = collections.Counter(words)

【问题讨论】:

  • 您也可以只计算单词而不将结果写入“merged.txt”文件.. 节省一些 io
  • 最好的方法是什么?

标签: python python-2.7 merge


【解决方案1】:
import os                                 
os.remove(file_to_remove) 

删除文件。

或:

import shutil
shutil.move(file_to_move,destination).

移动它。

os.remove , shutil.move

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 2016-08-10
    • 2015-12-27
    相关资源
    最近更新 更多