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:In your case, you wouldn’t use
fas you’re already usingffor your input file handle.I suppose you’d want something like: