Gunzip Python 中源目录中的所有文件

Gunzip all the files present in source directory in Python

我已经编写了一个代码来压缩源文件夹中存在的所有文件。但我想包括检查,如果 gunzipped 文件不存在,那么 gunzip 它否则移动到下一个文件。

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在这里不起作用。

我认为您放错了 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 所强调的: "doing the check after open(..., 'wb') (as you did in your original code), will always say that the file exists because that is what open(..., 'w') does"

最重要的是,即使您对 gunzipping 的必要性进行了一些其他检查,在您放置它的地方执行它也会对每一行进行检查,这是完全多余的,因为结果与所有行 (exists/not-exists).