Extracting zip files using python - python

I'm trying to get all zip files in a specific directory name "downloaded" and to extract all of their content to a directory named "extracted".
I don't know why, after I'm iterating only existing files name, I get an error that there is no such file...
allFilesList = os.listdir(os.getcwd()+"/downloaded")
print allFilesList #verify - correct expected list
from zipfile import ZipFile
os.chdir(os.getcwd()+"/extracted/")
print os.getcwd() #verify - correct expected dir
for fileName in allFilesList:
print fileName
with ZipFile(fileName, 'r') as zipFileObject:
if os.path.exists(fileName):
print "Skipping extracting " + fileName
continue
zipFileObject.extractall(pwd='hello')
print "Saving extracted file to extracted/",fileName
print "all files has been successfully extracted"
Error message:
File "program.py", line 77, in <module>
with ZipFile(fileName, 'r') as zipFileObject:
File "/usr/lib/python2.7/zipfile.py", line 779, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 2] No such file or directory: 'zipFile1.zip'

You're getting the list of filenames from one directory, then changing to another, and trying to extract the files from that directory that likely don't exist:
allFilesList = os.listdir(os.getcwd()+"/downloaded")
# ...
os.chdir(os.getcwd()+"/extracted/")
# ...
with ZipFile(fileName, 'r') as zipFileObject:
If you change that file ZipFile command to something like this:
with ZipFile(os.path.join("..", "downloaded", fileName), 'r') as zipFileObject:
You should be able to open the file in the directory you found it in.

Related

Decompressing .bz2 files in a directory in python

I would like to decompress a bunch of .bz2 files contained in a folder (where there are also .zst files). What I am doing is the following:
destination_folder = "/destination_folder_path/"
compressed_files_path="/compressedfiles_folder_path/"
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
if ".bz2" in file:
unpackedfile = bz2.BZ2File(file)
data = unpackedfile.read()
open(destination_folder, 'wb').write(data)
But I keep on getting the following error message:
Traceback (most recent call last):
File "mycode.py", line 34, in <module>
unpackedfile = bz2.BZ2File(file)
File ".../miniconda3/lib/python3.9/bz2.py", line 85, in __init__
self._fp = _builtin_open(filename, mode)
FileNotFoundError: [Errno 2] No such file or directory: 'filename.bz2'
Why do I receive this error?
You must be sure that all the file paths you are using exist.
It is better to use the full path to the file being opened.
import os
import bz2
# this path must exist
destination_folder = "/full_path_to/folder/"
compressed_files_path = "/full_path_to_other/folder/"
# get list with filenames (strings)
dirListing = os.listdir(compressed_files_path)
for file in dirListing:
# ^ this is only filename.ext
if ".bz2" in file:
# concatenation of directory path and filename.bz2
existing_file_path = os.path.join(compressed_files_path, file)
# read the file as you want
unpackedfile = bz2.BZ2File(existing_file_path)
data = unpackedfile.read()
new_file_path = os.path.join(destination_folder, file)
with bz2.open(new_file_path, 'wb') as f:
f.write(data)
You can also use the shutil module to copy or move files.
os.path.exists
os.path.join
shutil
bz2 examples

python seach file in directory - unable to open file [duplicate]

This question already has an answer here:
Using os.walk to find and print names of my files, but unable to open them? Path name issue?
(1 answer)
Closed 1 year ago.
I have file list:
import os
import fnmatch
files_template = ['a.txt','b.txt','c.txt','d.txt','e.txt','f.txt']
dir_path = '/users/john'
I need to open file specified in "files_template" list and parse its data but I am able to open the file
for root, dirs, files in os.walk(dir_path):
for file in files:
if file in files_template:
with open(file, 'r') as fh:
str = fh.read()
print(str)
I am getting below error message.
Traceback (most recent call last):
with open(file, 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'
how to fix it?
abs_file_path = os.path.join(root, file)
with open(abs_file_path, 'r') as fh:
...

Python suddenly cannot find files only when I want to rename or copy them

I'm trying to very simply copy a load of files from one directory to another and then rename the files (to replace whitespaces and %20 with _). In my root directory, I have:
optimiser.py (what I use to run the script)
Folder (named 'Files to Improve' containing basic text files)
Folder (named 'Finished' where I want every file to be copied to (empty))
It seems that the files can be found because this code successfully prints every file (and their respective new filenames):
import os
from shutil import copyfile
files_to_improve_dir = 'Files to Improve'
finished_files_dir = 'Finished'
for f in os.listdir(files_to_improve_dir):
new_filename = f.replace(' ','_').replace('%20','_').lower()
print('f:', f, '--- n:', new_filename)
The first problem occurs when I add copyfile(f, finished_files_dir) to the bottom, returning this error:
f: FILE.txt --- n: file.txt
Traceback (most recent call last):
File "optimiser.py", line 10, in <module>
copyfile(f, finished_files_dir)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/shutil.py", line 259, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: 'FILE.txt'
Does anyone know what this error is and why it occurs?
Secondly, if I instead add this to the bottom instead of the copy file line:
if (f != new_filename):
os.rename(f, new_filename)
It returns this error instead:
f: FILE.txt --- n: file.txt
Traceback (most recent call last):
File "optimiser.py", line 12, in <module>
os.rename(f, new_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'FILE.txt' -> 'file.txt'
I don't know why it suddenly now cannot find the files, despite it printing them in the previous code. If it couldn't find the files, how could it have printed them?
Thanks for any help here. The complete code is below:
import os
from shutil import copyfile
files_to_improve_dir = 'Files to Improve'
finished_files_dir = 'Finished'
for f in os.listdir(files_to_improve_dir):
new_filename = f.replace(' ','_').replace('%20','_').lower()
print('f:', f, '--- n:', new_filename)
copyfile(f, finished_files_dir) #error 1
if (f != new_filename): #error 2
os.rename(f, new_filename) #error 2
Change your
copyfile(f, finished_files_dir) #error 1
to
copyfile(os.path.join(files_to_improve_dir, f),
os.path.join(finished_files_dir, f))
and
os.rename(f, new_filename) #error 2
to
os.rename(os.path.join(files_to_improve_dir, f),
os.path.join(files_to_improve_dir, new_filename))
One more hint: When renaming your file, there might araise duplicates (e.g. bla bla and bla%20bla will both be renamed to bla_bla), so you may want to check if the destination exists already...

Python IOError: [Errno 2] from recursive directory call

The code below is part of a program I am writing that runs a method on every .py, .sh. or .pl file in a directory and its folders.
for root, subs, files in os.walk("."):
for a in files:
if a.endswith('.py') or a.endswith('.sh') or a.endswith('.pl'):
scriptFile = open(a, 'r')
writer(writeFile, scriptFile)
scriptFile.close()
else:
continue
When writing the program, it worked in the directory tree I wrote it in, but when I moved it to another folder to try it there I get this error message:
Traceback (most recent call last):
File "versionTEST.py", line 75, in <module>
scriptFile = open(a, 'r')
IOError: [Errno 2] No such file or directory: 'enabledLogSources.sh'
I know something weird is going on because the file is most definitely there...
You'll need to prepend the root directory to your filename
scriptFile = open(root + '/' + a, 'r')
files contains only the file names, not the entire path. The path to the file can be obtained by joining the file name and the root:
scriptFile = open(os.path.join(root, a), "r")
You might want to have a look at
https://docs.python.org/2/library/os.html#os.walk

IOError: [Errno 2] No such file or directory [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 9 years ago.
im having problems trying to run an iteration over many files in a folder, the files exist, if I print file from files I can see their names...
Im quite new to programming, could you please give me a hand? kind regards!
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
fdf = open(file, "r")
IOError: [Errno 2] No such file or directory: 'FDF_20110612_140613_...........txt'
You need to prefix each file name with path before you open the file.
See the documentation for os.walk.
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
filepath = os.path.join(path, file)
print filepath
fdf = open(filepath, "r")
Try this:
import os
for path, dirs, files in os.walk('FDF\FDF'):
for file in files:
print file
with open(os.path.join(path, file)) as fdf:
# code goes here.

Categories