Compress file to zip - python

i'm trying to do a program here i need to compress some files, but i want it to stop when the file doesn't exist.
The code works, but the thing is that it compresses the file anyway, what i mean is that the program outputs the error but compress a file with that name (an empty file)
if someone could help it would be wonderful :)
import sys, zipfile
def compress (file):
try:
zf = zipfile.ZipFile(file + '.zip', mode='w')
zf.write(file, compress_type=zipfile.ZIP_DEFLATED)
zf.close()
except OSError:
print("The file "+ file + " doesnt exist!")
#erro.value = 1
if __name__ == "__main__":
compress(sys.argv[1])

From Python documentation:
If the file is created with mode 'w', 'x' or 'a' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.
So use
if os.path.exists(file)
to check if the file exists, before
zf = zipfile.ZipFile(file + '.zip', mode='w')

Related

Walk directories and remove file extensions

I'm trying to remove all the outlook .ost and .nst files from the user's folder on a network PC, as well as I'm trying to get it to write what files were removed into a CSV file.
I'm able to get it to find all the files in the directory and write it to a CSV file but when I try to remove the files with os.remove it doesn't seem to run, I hashed it out for the time being.
I added in the try and except, to skip the files that are in use.
import os
import sys
sys.stdout = open("output_file.csv", "w")
try:
for rootDir, subdir, files in os.walk("//network_pc_name/c$/Users"):
for filenames in files:
if filenames.endswith((".nst",".ost")):
foundfiles = os.path.join(rootDir, filenames)
#os.remove(os.path.join(rootDir, filenames))
print(foundfiles)
except:
pass
sys.stdout.close()
I made some change to the script as suggested and it appears to run alot quicker, however, I can't seem to figure out how to ignore files which are in use.
I switched the files extensions to .xlsx and .txt files to simulate the .xlsx file being open receiving the permissions error and to see if the script would continue to run and remove the .txt file.
I got the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '//DESKTOP-HRLS19N/c$/globtest\Book1.xlsx
import glob
import os
files = [i for i in glob.glob("//DESKTOP-HRLS19N/c$/globtest/**", recursive = True) if i.endswith((".xlsx",".txt"))]
[os.remove(f) for f in files]
with open("output_file.csv", "w") as f:
f.writelines("\n".join(files))
In my experience glob is much easier:
print([i for i in glob.glob("//network_pc_name/c$/Users/**", recursive=True) if i.endswith((".nst", ".ost"))])
Assuming that prints out the files you're expecting:
files = [i for i in glob.glob("//network_pc_name/c$/Users/**", recursive=True) if i.endswith((".nst", ".ost"))]
removed_files = []
for file in files:
try:
size = os.path.getsize(file)
os.remove(file)
removed_files.append(file + " Bytes: " + size)
except Exception as e:
print("Could not remove file: " + file)
with open("output_file.csv", "w") as f:
f.writelines("\n".join(removed_files))

Unable to load contents while reading a .txt file in Python3

I am intending to extract some data stored in a .txt file using python 3, however, when I tried to print out the file content, the program does not display any thing in the console. This is the code snippet I use to read the file:
def get_data(directory):
entries = os.listdir(directory)
#print(entries)
count = 0;
for file in entries:
#print(file)
if file.endswith('.txt'):
with open(file) as curr_file:
#print(curr_file)
#read data and write it to an
#excel worksheet
print(curr_file.readline())
curr_file.close()
What kind of changes am I supposed to make to let the program display contents of the file?
Update: I tried to print out all files saved in entries and the result looks fine. The following is the code snippet I used to unzip files in the directory, I am not sure whether there're anything wrong with it.
def read_zip(path):
file_list = os.listdir(path)
#print(file_list)
#create a new directory and store
#the extracted file there
directory = 'C:/Users/chent/Desktop/Test'
try:
if not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
print('Folder created')
except FileExistsError:
print ('Directory not created')
for file in file_list:
if file.endswith('.zip'):
filePath=path+'/'+file
zip_file = zipfile.ZipFile(filePath)
for names in zip_file.namelist():
zip_file.extract(names, directory)
get_data(directory)
zip_file.close()
Solution: It turns out that I didn't specify the file path when use with open() statement, which caused the program unable to locate files. To fix it, use with open(file_path, file, "r") as curr_file. See details in my updated code:
def get_data(path):
files = os.listdir(path)
for file in files:
#print(file)
try:
if file.endswith('.txt'):
print(file)
with open('C:/Users/chent/Desktop/Test/' + file, "r", ) as curr_file:
# print(curr_file.readlines())
print(curr_file)
line = curr_file.readline()
print(line)
except FileNotFoundError:
print ('File not found')
path = 'C:/Users/chent/Desktop/Test'
get_data(path)
The problem is that you use curr_file.readline() which only returns the first line.
Use curr_file.read() to get the whole file contents.

Changing file extensions, content being deleted

I am stole a little script that is supposed to simply add an extension where none exists from a file export. But when I run it, I get results and the actual content from the files has thus been zeroed out.
Why is this happening?
import os, sys
path = 'C:/Users/jal!/Downloads/Sinopiadata/'
for file in os.listdir(path):
if file != "complete.log" and file != "jasawn.py":
os.chdir('C:/Users/jal!/Downloads/Sinopiadata/')
file = (file)
filename = file + ".json"
filename = open(filename,'w')
There's always the rename method you can (or should, as mentioned in the comments) use:
import os
os.rename(file, file_with_extension)
You haven't put anything into the new file. If you want to copy from the file without the extension to the file with the extension, you have to read and write.
for file in os.listdir(path):
if file != "complete.log" and file != "jasawn.py":
os.chdir('C:/Users/jal!/Downloads/Sinopiadata/')
file = (file)
filename = file + ".json"
with open(filename,'w') as newfile, open(file, 'r') as oldfile:
newfile.write(oldfile.read())
You can also use shutil.copyfile()
filename = open(filename,'w')
opens the file for writing in truncating mode, which is why it gets emptied. There's no point in having that line there at all if you're only renaming things. You should just use os.rename(old_path, new_path).

File not found while looping through folder of .txt files?

I wrote a program to loop through a folder of text files, and for each one, read it and write its edited contents to a new txt file. When I write to a new file, I add "JSP" to the file name, and so I included an if statement to avoid editing a file with JSP in its name. It gives me an error message that suggests that it tried to do the method writeToFile on a JSP file, and it couldn't be found within the folder. This confuses me because
if it's looping through the files and gets to that specific file, it should exist, and
it shouldn't even enter the if statement if it has "JSP" in its filename.
Any ideas?
import program
import os
def main():
directoryStr = "/Users/Elle/Documents/TMR/txtfiles/untitled folder"
directory = os.fsencode(directoryStr)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if ".txt" in filename and "JSP" not in filename:
storedProcedure = program.StoredProcedure(filename)
storedProcedure.writeToFile()
main()
newFile = open(self.newName + ".txt", "w", encoding="utf16")
FileNotFoundError: [Errno 2] No such file or directory: 'JSP_Pgm_JpgmAPARCustSummary_Ctrl_Pay/Rec_summedbycustid_LtorGr0.txt'
Try doing things this way — as I said in a comment, os.listdir() only gives you a list of filenames, not complete file paths.
import program
import os
def main():
directory = "/Users/Elle/Documents/TMR/txtfiles/untitled folder"
for filename in os.listdir(directory):
if ".txt" in filename and "JSP" not in filename:
filepath = os.path.join(directory, filename)
storedProcedure = program.StoredProcedure(filepath)
storedProcedure.writeToFile()
main()

Cannot find a file in my tempfile.TemporaryDirectory() for Python3

I'm having trouble working with Python3's tempfile library in general.
I need to write a file in a temporary directory, and make sure it's there. The third party software tool I use sometimes fails so I can't just open the file, I need to verify it's there first using a 'while loop' or other method before just opening it. So I need to search the tmp_dir (using os.listdir() or equivalent).
Specific help/solution and general help would be appreciated in comments.
Thank you.
Small sample code:
import os
import tempfile
with tempfile.TemporaryDirectory() as tmp_dir:
print('tmp dir name', tmp_dir)
# write file to tmp dir
fout = open(tmp_dir + 'file.txt', 'w')
fout.write('test write')
fout.close()
print('file.txt location', tmp_dir + 'lala.fasta')
# working with the file is fine
fin = open(tmp_dir + 'file.txt', 'U')
for line in fin:
print(line)
# but I cannot find the file in the tmp dir like I normally use os.listdir()
for file in os.listdir(tmp_dir):
print('searching in directory')
print(file)
That's expected because the temporary directory name doesn't end with path separator (os.sep, slash or backslash on many systems). So the file is created at the wrong level.
tmp_dir = D:\Users\foo\AppData\Local\Temp\tmpm_x5z4tx
tmp_dir + "file.txt"
=> D:\Users\foo\AppData\Local\Temp\tmpm_x5z4txfile.txt
Instead, join both paths to get a file inside your temporary dir:
fout = open(os.path.join(tmp_dir,'file.txt'), 'w')
note that fin = open(tmp_dir + 'file.txt', 'U') finds the file, that's expected, but it finds it in the same directory where tmp_dir was created.

Categories

Resources