【问题标题】:function is not able to properly write output data file - Python函数无法正确写入输出数据文件 - Python
【发布时间】:2018-06-01 09:58:55
【问题描述】:

场景:

我有两个文件,file1 size = 19.7MBfile2 size = 446KB。我正在运行以下代码来处理两个文件中的数据并获取输出数据文件。但是在一定的输出文件大小(332KB)之后,程序停止将数据写入输出文件。我尝试使用flush() 函数,但输出文件再次包含与输出文件完全相同的大小,而没有使用flush() 函数(并且在两种情况下(创建文件和最后修改的文件)都花费了完全相同的时间来写入这些数据),而循环是仍在运行。

请有人提出可能的原因?我应该使用sleep()函数在一定时间后唤醒程序吗?谢谢

with open("file2",'rU') as gg:
    for g in gg:
        g = g.rstrip().split('\t')
        with open(file1) as cc:
            c = c.rstrip().split('\t')
                if int(c[0]) == int(g[0]) and int(c[1]) >= int(g[2]) and int(g[3]) >= int(c[1]):
                    with open('output.txt', 'a') as ii:
                        ii.write(c[1]+'\t'+'\t'.join(g)+'\n')
                        ii.flush()

【问题讨论】:

  • 您还在访问if 条件吗?
  • 而且我认为您在c = c.rstrip().split('\t') 中的代码实际上应该是c = cc.rstrip().split('\t')
  • 由于您有条件地写入输出文件,因此该条件似乎只满足(很少?)次,即总输出实际上是 332KB。

标签: python flush


【解决方案1】:

您正在为同一个文件创建太多连接,并且此类操作存在操作系统限制。

尝试尽可能多地取消嵌套脚本

    new_list = []
    with open("file2",'rU') as gg:
        for g in gg:
            g = g.rstrip().split('\t')
            with open(file1) as cc:
                c = cc.rstrip().split('\t')
                if int(c[0]) == int(g[0]) and int(c[1]) >= int(g[2]) and int(g[3]) >= int(c[1]):
                    new_list.append(c[1]+'\t'+'\t'.join(g)+'\n')

    with open('output.txt', 'a') as ii:
        for e in new_list:
                    ii.write(e)

【讨论】:

  • 虽然总体建议是合理的,但看起来并没有太多连接(一次)。只是对同一个文件有很多打开-关闭操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2020-05-10
  • 1970-01-01
  • 2018-11-15
  • 1970-01-01
相关资源
最近更新 更多