Python: how to create a new file and write contents of variable to it?

python

Solution

In general, if you have a string in a variable `foo`, you can write it to a file with:

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

In your case, you wouldn't use `f` as you're already using `f` for your input file handle.

I suppose you'd want something like:

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)

Problem

I am writing a program that outputs the file types inside a directory by looking at their headers. Some of the files are compressed so I need to be able to decompress them as a starting point So far I have been able to search directories and using the header change the extensions, and open the compressed file and store its contents in a variable, now I am having trouble saving the variable as a new file. ``` 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) ``` I'm guessing I will have to use the a command along the lines of `f.write("newfile", content)` but not sure. Thanks in advance

Original source