2017-09-22 59 views
0

我已经写了一个代码来gunzip源文件夹中存在的所有文件。但我想包括检查,如果gunzip文件不存在,然后gunzip它移动到下一个文件。Gunzip Python源文件夹中的所有文件

source_dir = "/Users/path" 
dest_dir = "/Users/path/Documents/path" 


for src_name in glob.glob(os.path.join(source_dir, '*.gz')): 

    base = os.path.basename(src_name) 
    dest_name = os.path.join(dest_dir, base[:-3]) 
    with: gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile: 
      try: 
       for line in infile: 
        print ("outfile: %s" %outfile) 
        if not os.path.exists(dest_name): 
         outfile.write(line) 
         print("converted: %s" %dest_name) 

      except EOFError: 
       print("End of file error occurred.") 

      except Exception: 
       print("Some error occurred.") 

我已经使用os.path.exist检查文件是否存在,但它似乎是os.path.exist不在这里工作了。

+0

对于问题2,使用您的操作系统的计划作业实用程序。无需尝试编程自己的。 – glibdud

+0

第1部分没有问题。第2部分对于堆栈溢出来说过于宽泛。 –

+0

@MadPhysicist,我想添加一个检查,如果gunzip文件不存在,那么只有gunzip它明智的移动到下一个文件。如何检查这个? – rnvs1116

回答

1

我认为你错位了path.exists电话。它应该是:

source_dir = "/Users/path" 
dest_dir = "/Users/path/Documents/path" 


for src_name in glob.glob(os.path.join(source_dir, '*.gz')): 

    base = os.path.basename(src_name) 
    dest_name = os.path.join(dest_dir, base[:-3]) 

    if not os.path.exists(dest_name): 
     with gzip.open(src_name, 'rb') as infile, open(dest_name, 'wb') as outfile: 
      try: 
       for line in infile: 
        print("outfile: %s" % outfile) 
        outfile.write(line) 
        print("converted: %s" % dest_name) 

      except EOFError: 
       print("End of file error occurred.") 

      except Exception: 
       print("Some error occurred.") 

另外,作为@MadPhysicist强调: “后做的检查开(...,‘WB’)(如你在原来的代码一样),总是会说该文件存在因为这是开放的(...,'w')“

最重要的是,即使你做了一些其他检查是否需要进行gunzipping,在你放置它的地方进行检查每行都是完全冗余的,因此结果对于所有行都是相同的(存在/不存在)。

+0

OP的代码比你的优雅得多。 –

+0

我没有更改现有的代码,只举了一个如何使用setup来设置他需要的文件列表的例子。我所做的只是在for_loop之前添加5行。原本没有提供他想要的东西。 – ronenmiller

+0

@MadPhysicist最初没有看到OP的问题。修正了我的答案,如果陈述错位。请重新检查并给出您的想法。 – ronenmiller

相关问题