8

我正在编写一个程序,通过查看它们的标题来输出目录中的文件类型。

一些文件是压缩的,所以我需要能够解压缩它们作为起点

到目前为止,我已经能够搜索目录并使用标题更改扩展名,打开压缩文件并将其内容存储在变量中,现在我无法将变量保存为新文件。

def unzip():
    os.chdir("C:/Users/David/Myfiles")
    files = os.listdir(".")
    for x in (files):
        f = open((x), "rb")
        byte1 = f.read(1)
        byte2 = f.read(1)
        if byte1 == b'\x1f' and byte2 == b'\x8b':
            os.rename((x), (x) + ".gz")
            file = gzip.open((x), "rb")
            content = file.read()   
            print (content)

我猜我将不得不按照f.write("newfile", content)但不确定的方式使用 a 命令。

提前致谢

4

3 回答 3

12

通常,如果变量中有一个字符串,foo则可以将其写入文件:

with open('output.file','w') as f:
    f.write(foo)

在你的情况下,你不会使用f你已经在使用f你的输入文件句柄。

我想你会想要这样的东西:

def unzip():
    os.chdir("C:/Users/Luke/Desktop/Cache")
    files = os.listdir(".")
    for x in (files):
        ifh = open((x), "rb")
        byte1 = ifh.read(1)
        byte2 = ifh.read(1)
        if byte1 == b'\x1f' and byte2 == b'\x8b':
            os.rename((x), (x) + ".gz")
            file = gzip.open((x), "rb")
            contents = file.read()   
            with open('output.file','w') as ofh:
                ofh.write(contents)
于 2012-11-28T20:27:48.137 回答
1

您应该执行以下操作:

with open('filename.whatever', 'wb') as output:
    output.write(your_data)

在http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files查看文档

于 2012-11-28T20:29:24.680 回答
1

您不必查看前两个字节来识别 gz 文件。相反,我认为更“Pythonic”的方法是先尝试,然后道歉(通常称为“更容易请求宽恕而不是许可”):

import os
import bz2
import gzip

def write(filename, content):
    with open(filename, 'w') as g:
        g.write(content)

def uncompress(dirpath):
    for filename in os.listdir(dirpath):
        filename = os.path.join(dirpath, filename)
        for opener in (gzip.open, bz2.BZ2File):
            try:
                with opener(filename) as f:
                    newfile, ext = os.path.splitext(filename)
                    content = f.read()
                os.unlink(filename)
                write(newfile, content)
            except IOError:
                continue
            else: # break if try worked without IOError        
                break

dirpath = "C:/Users/Luke/Desktop/Cache"
uncompress(dirpath)

此外,如果可能,最好避免使用os.chdir,因为即使您离开该uncompress功能,它也会改变当前目录。如果您的脚本处理其他目录,那么您必须在程序的每个阶段仔细控制当前目录是什么。如果您os.path.join改用,您永远不必担心当前目录是什么。

于 2012-11-28T20:36:08.183 回答