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

I am writing a program that displays file types inside a directory by looking at their headers.

Some of the files are compressed, so I need to unzip them as a starting point

So far I have managed to search directories and use the title to change the extensions, and open the compressed file and save its contents in a variable, now I can not save 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 assume that I will have to use the a command line by line f.write("newfile", content) , but not sure.

Thank you in advance

+4
source share
3 answers

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

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

In your case, you will not use f , since you are already using f for your input file descriptor.

I suppose you need 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) 
+7
source

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

+1
source

You do not need to search for the first two bytes to identify gz files. Instead, I think a more “pythonic” approach would be to try first, apologize later (better known as “It's 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 best to avoid using os.chdir if possible, because it changes the current directory even after you leave the uncompress function. If your script deals with other directories, you should carefully monitor that the current directory is at each stage of your program. If you use os.path.join , you never have to worry about what the current directory is.

+1
source

All Articles