I am having a situation in ensuring that when I create a zip file it does not have the whole directory of the file when it is unzipped.
Having done some research there is a lot of content about using arcname in zip.write, however any solution I try results in the whole server being zipped!
I have tried adding arcname = os.path.basename(file) and other possible solutions with no luck.
This is my code below:
all_order_files = glob.glob("/directory/"+str(order_submission.id)+"-*")
zip = zipfile.ZipFile("/directory/" + str(order_submission.id) + '-Order-Summary.zip', 'w')
for file in all_order_files:
zip.write(file)
zip.close()
After reading this answer: Create .zip in Python?
I adapted the code to read the following which solved the issue for me.
all_order_files = glob.glob("/directory/"+str(order_submission.id)+"-*")
zip = zipfile.ZipFile("/directory/" + str(order_submission.id) + '-Order-Summary.zip', 'w')
path = "/directory/"
for file in all_order_files:
file_name = file.split('/')[-1]
absname = os.path.abspath(os.path.join(path, file_name))
arcname = absname[len(path) + 1:]
zip.write(absname, arcname)
zip.close()
Noting the extra argument provided to the write function that changes the directory structure when the zip file is unzipped.
Related
I have my python code that runs a C++ code, which takes files in another folder as input.
I have my codes in folder A, and the input files are in folder B, and I have been trying this:
path = 'C:/pathToInputFiles'
dirs = os.listdir(path)
for path in dirs:
proc = subprocess.Popen([fullPathtoCppCode, inputFiles])
However, I keep receiving WindowsError: [Error 2] The system cannot find the file specified
The only way it works is when I put the C++ executable file in the same folder of the input files, which I am avoiding to do.
How can I make python reads the file path properly?
Try using os.path.join after your for statement.
path = os.path.join(directory, filename)
for example
def test(directory):
for filename in os.listdir(directory):
filename = os.path.join(directory, filename)
proc = subprocess.Popen([fullPathtoCppcode, inputFiles])
I am trying to set up a program to put my minecraft server world into a zip and place it into another directory on another drive (/media/500gb/MinecraftWorldBackups)
But I keep getting this error
Although the folder doesn't contain a folder or file called 'h'
What do I need to do to fix this I believe it is due to file and folder?
#!/usr/bin/env python
import time, zipfile
while True:
FileName = 'MinecraftBackup_' + str(int(time.time()))
Path = '/home/bertie/Desktop/FeedTheBeastServer/world/'
print(FileName)
Zip = zipfile.ZipFile('/media/500gb/MinecraftWorldBackups/'+FileName+'.zip','w')
for each in Path:
print(each)
try: Zip.write(Path + each)
except IOError: None
Zip.Close()
print('Done')
time.sleep(60)
My problem is to read '.csv' files in catalogs and do some calculations on them.
I have calculations working but my for loop seem not to work as I want to.
d = 'F:\MArcin\Experiments\csvCollection\'
for dirname, dirs, files in os.walk(d):
for i in files:
if i.endswith('.csv'):
data1 = pd.read_csv(i, sep=",")
data = data1['x'][:, np.newaxis]
target = data1['y']
The error Iam getting is:
IOError: File 1.csv does not exist
files is list of all '.csv' files inside dirname
i is str of size 1 and contains 1.csv (that is first of the files in catalog)
Any ideas why this is not working?
Thanks for any help.
Because 1.csv is somewhere on the filesystem and when you call read_csv() it opens file relative to current directory.
Just open it using absolute path:
data1 = pd.read_csv(os.path.join(dirname, i), sep=",")
dirname in os.walk represents actual directory where file 1.csv is located.
I use the following code for downloading two files in a folder from a website.
I want to download some files that contain "MOD09GA.A2008077.h22v05.005.2008080122814.hdf" and "MOD09GA.A2008077.h23v05.005.2008080122921.hdf" in the page. But I don't know how to select these files. The code below download all the files, but I only need two of them.
Does anyone have any ideas?
URL = 'http://e4ftl01.cr.usgs.gov/MOLT/MOD09GA.005/2008.03.17/';
% Local path on your machine
localPath = 'E:/myfolder/';
% Read html contents and parse file names with ending *.hdf
urlContents = urlread(URL);
ret = regexp(urlContents, '"\S+.hdf.xml"', 'match');
% Loop over all files and download them
for k=1:length(ret)
filename = ret{k}(2:end-1);
filepathOnline = strcat(URL, filename);
filepathLocal = fullfile(localPath, filename);
urlwrite(filepathOnline, filepathLocal);
end
Try the regexp with tokens instead:
localPath = 'E:/myfolder/';
urlContents = 'aaaa "MOD09GA.A2008077.h22v05.005.2008080122814.hdf.xml" and "MOD09GA.A2008077.h23v05.005.2008080122921.hdf.xml" aaaaa';
ret = regexp(urlContents , '"(\S+)(?:\.\d+){2}(\.hdf\.xml)"', 'tokens');
%// Loop over each file name
for k=1:length(ret)
filename = [ret{k}{:}];
filepathLocal = fullfile(localPath, filename)
end
I recently wrote a python script to select certain files within a directory and save them to a new archive within that directory. The script works with the exception that it creates a duplicate archive within the new archive. I think it has something to do with the arcname I used and the loop but I'm really not sure. As I'm sure is obvious by looking at my code I am a beginner so I am sure there is plenty of room for improvement here. Any ideas as to where the problem is? Also if you have any suggestions for improving the code I'm all ears.
import os,arcpy,zipfile
inputfc = arcpy.GetParameterAsText(0) # User Inputs Feature Class Path
desc = arcpy.Describe(inputfc)
fcname = desc.basename
zname = fcname + ".zip"
gpath = os.path.dirname(inputfc)
zpath = os.path.join(gpath,zname)
zfile = zipfile.ZipFile(zpath, "w")
for f in os.listdir(gpath):
fpath = os.path.join(gpath, f)
if f.startswith(fcname):
zfile.write(fpath,f,compress_type = zipfile.ZIP_DEFLATED)
zfile.close()
Edit: After aruisdante answered my question I decided to just change the zname variable to
zname = "zip" + fcname + ".zip" #ugly but it worked thanks
This:
zfile = zipfile.ZipFile(zpath, "w")
Creates a new Zip file at zpath
for f in os.listdir(gpath):
Iterates through all of the files at gpath. Since gpath is also the root of zpath, then the zip file you just created will be one of the files in gpath. So it gets included in the archive. You will need to exclude it:
for f in (filename for filename in os.listdir(gpath) if filename != zname):