简体   繁体   中英

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

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

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)

you should do something like:

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

check out the docs at http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

You do not have to look at the first two bytes to identify gz files. Instead, I think a more "Pythonic" approach would be to try first, apologize later (more commonly known as "Easier to ask Forgiveness than Permission" ):

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)

Also, it is better to avoid using os.chdir if possible because it alters the current directory even after you leave the uncompress function. If your script deals with other directories, then you have to carefully control what the current directory is at every stage of your program. If you use os.path.join instead, you never have to worry about what is the current directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM