Python: How make a zip with file, not into folder - python

Folder contain my files and I want to make a zip with those files, and save zip into a folder.
Here my files
- file:
- file_0.txt
- file_1.txt
- file_2.txt
- zip:
// save zip
script.py
Here my code
from zipfile import ZipFile
zip_name = "Zipfile"
zipObj = ZipFile("zip/{}.zip".format(zip_name), "w")
count = 0
while count < 3:
file_name = "file_"
zipObj.write('file/' + file_name + str(count) + ".txt")
count += 1
This make a Zip file with a folder named file, and inside all txt, I want to remove folder and only zip the files

from zipfile import ZipFile
zip_name = "Zipfile"
zipObj = ZipFile("zip/{}.zip".format(zip_name), "w")
count = 0
import os
os.chdir('file')
while count < 3:
file_name = "file_"
zipObj.write(file_name + str(count) + ".txt")
count += 1
This should work for you

Related

Rename substring of actual files - python

I am reading in all the files in a given folder:
import os
path = '/Users/user/Desktop/folder_name'
files = os.listdir(path)
I have multiple files (100+) with the following names:
20220330_a.txt 20220330_b.txt 20220330_c.txt
I want to replace the "20220331" to "20220630" in the actual file names in the folder, so I obtain 20220630_a.txt, 20220630_b.txt etc.
Any ideas?
I figured it out myself:
old_date = "20200331"
new_date = "20200630"
for file in os.listdir(path):
if file.startswith(old_date):
if file.find(old_date) > -1:
counter = counter + 1
os.rename(os.path.join(path, file), os.path.join(path, file.replace(old_date,new_date)))
if counter == 0:
print("No file has been found")

os.walk Python can't print all drivers

Im using os module to get all the files in a directory
drives = [ chr(x) + ":\" for x in range(65,91) if os.path.exists(chr(x) + ":\") ]
print(drives)
prints out
['C:\', 'D:\']
then I look for all the files in those disks with
counter = 0
inp = '.png'
thisdir = os.getcwd()
for r, d, f in os.walk(drives[0-1]):
for file in f:
filepath = os.path.join(r, file)
if inp in file:
counter += 1
print(os.path.join(r, file))
print(f"counted {counter} files.")
but I get only D:\ drives '.png' file's which print's out 55.000 of pictures location on the drive I cant get c:\ what am I doing here wrong I'm a bit python newbie right now so I don't know what to do can someone help me please?
To reply to your comment, this is how you'd loop over drive:
counter = 0
inp = '.png'
for drive in drives:
for r, d, f in os.walk(drive):
for file in f:
filepath = os.path.join(r, file)
if inp in file:
counter += 1
print(os.path.join(r, file))
print(f"counted {counter} files.")

Python - Compare filenames in lists

I have code which check if files contents are the same. Files have the same filename in both folders.
For example:
folder JSON1/test1.txt
folder JSON2/test1.txt
For a single file this works, but I would like to apply it to a list of files.
So in the JSON1 folder I will have:
JSON1 / test.txt
JSON1 / second.txt
JSON1 / result.txt
And in the JSON2 folder I will have the same file list.
Can you help how to change it to handle multiple files?
import os
import sys
filenameODS = "C:/Users/adm/Json1/" + sys.argv[1] + ".txt"
filenameDWH = "C:/Users/adm/Json2/" + sys.argv[1] + ".txt"
file1contents = set(open(filenameODS).readlines())
file2contents = set(open(filenameDWH).readlines())
if file1contents == file2contents:
print("Files are the same!")
else:
print("In file2, not file1:\n")
for diffLine in file2contents - file1contents:
print ("\t", diffLine)
print ("\nIn file1, not file2:\n")
for diffLine in file1contents - file2contents:
print ("\t", diffLine)
with open('C:/Users/adm/Json3/'+ sys.argv[1] + '.txt', 'w') as f:
f.write(diffLine)
f.close()

How to unzip all files from the same filetype with python

I want to extract all files that have the same filetype from a zip file.
I have this code:
from zipfile import ZipFile
counter = 0
with ZipFile('Video.zip', 'r') as zipObject:
listOfFileNames = zipObject.namelist()
for fileName in listOfFileNames:
if fileName.endswith('.MXF'):
zipObject.extract(fileName, 'Greenscreen')
print('File ' + str(counter) + ' extracted')
counter += 1
print('All ' + str(counter) + ' files extraced')
The problem is that the zip file also has multiple sub-folders with the required .MXF files in them.
Thus after running the script my Greenscreen folder also shows all sub-folders like this:
But i just need the files of the same file-type. So it should look like this:

Python - I'm trying to unzip a file that has multiple zip files within

My goal is to get to a txt file that is withing the second layer of zip files. The issue is that the txt file has the same name in all the .zip, so it overwrites the .txt and it only returns 1 .txt
from ftplib import *
import os, shutil, glob, zipfile, xlsxwriter
ftps = FTP_TLS()
ftps.connect(host='8.8.8.8', port=23)
ftps.login(user='xxxxxxx', passwd='xxxxxxx')
print ftps.getwelcome()
print 'Access was granted'
ftps.prot_p()
ftps.cwd('DirectoryINeed')
data = ftps.nlst() #Returns a list of .zip diles
data.sort() #Sorts the thing out
theFile = data[-2] #Its a .zip file #Stores the .zip i need to retrieve
fileSize = ftps.size(theFile) #gets the size of the file
print fileSize, 'bytes' #prints the size
def grabFile():
filename = 'the.zip'
localfile = open(filename, 'wb')
ftps.retrbinary('RETR ' + theFile, localfile.write)
ftps.quit()
localfile.close()
def unzipping():
zip_files = glob.glob('*.zip')
for zip_file in zip_files:
with zipfile.ZipFile(zip_file, 'r')as Z:
Z.extractall('anotherdirectory')
grabFile()
unzipping()
lastUnzip()
After this runs it grabs the .zip that I need and extracts the contents to a folder named anotherdirectory. Where it holds the second tier of .zips. This is where I get into trouble. When I try to extract the files from each zip. They all share the same name. I end up with a single .txt when I need one for each zip.
I think you're specifying the same output directory and filename each time. In the unzipping function,
change
Z.extractall('anotherdirectory')
to
Z.extractall(zip_file)
or
Z.extractall('anotherdirectory' + zip_file)
if the zip_file's are all the same, give each output folder a unique numbered name:
before unzipping function:
count = 1
then replace the other code with this:
Z.extractall('anotherdirectory/' + str(count))
count += 1
Thanks to jeremydeanlakey's response, I was able to get this part of my script. Here is how I did it:
folderUnzip = 'DirectoryYouNeed'
zip_files = glob.glob('*.zip')
count = 1
for zip_file in zip_files:
with zipfile.ZipFile(zip_file, 'r') as Z:
Z.extractall(folderUnzip + '/' + str(count))
count += 1

Categories