Python zipfile crashes gives an error for some files - python

I have a simple code to zip files using zipfile module. I am able to zip some files but I get FileNotFound error for the others. I have checked if this is file size error but its not.
I can pack files with name like example file.py but when I have a file inside a directory like 'Analyze Files en-US_es-ES.xlsx' if fails.
It works when I change os.path.basename to os.path.join but I don't want to zip whole folder structure, I want to have flat structure in my zip.
Here is my code:
import os
import zipfile
path = input()
x=zipfile.ZipFile('new.zip', 'w')
for root, dir, files in os.walk(path):
for eachFile in files:
x.write(os.path.basename(eachFile))
x.close()
Error looks like this:
Traceback (most recent call last):
File "C:/Users/mypc/Desktop/Zip test.py", line 15, in <module>
x.write(os.path.basename(eachFile))
File "C:\Python34\lib\zipfile.py", line 1326, in write
st = os.stat(filename)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Analyze Files en-US_ar-SA.xlsx'*

Simply change working directory to add file without original directory structure.
import os
import zipfile
path = input()
baseDir = os.getcwd()
with zipfile.ZipFile('new.zip', 'w') as z:
for root, dir, files in os.walk(path):
os.chdir(root)
for eachFile in files:
z.write(eachFile)
os.chdir(baseDir)

Related

Unable to open or read log files: FileNotFoundError [duplicate]

I'm trying to run the following script which simply reads and image and saves it again:
from PIL import Image
import os
rootdir = '/home/user/Desktop/sample'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
im = Image.open(file)
im.save(file)
I however get the following error:
Traceback (most recent call last):
File "test.py", line 10, in <module>
im = Image.open(file)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 2258, in open
fp = builtins.open(filename, "rb")
IOError: [Errno 2] No such file or directory: '1.jpg'
So, what I'm trying to do is simply read the file 1.jpg and save it again, provided that 1.jpg is located in the directory.
How can I fix this issue?
Thanks.
You're going to need to provide a fully qualified path, because file holds only the tail, not the entire path.
You can use os.path.join to join the root to the tail:
for root, dirs, files in os.walk(rootdir):
for file in files:
path = os.path.join(root, file)
im = Image.open(path)
im.save(path)

Why does do I have an IO error saying my file doesn't exist even though it does exist in the directory?

I am trying to loop over a Python directory, and I have a specific file that happens to be the last file in the directory such that I get an IOerror for that specific file.
The error I get is:
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My script:
for filename in os.listdir("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"):
data = []
if filename.endswith(".csv"):
data.append(k_fold(filename))
continue
else:
continue
k_fold does this:
def k_fold(myfile, myseed=11109, k=20):
# Load data
data = open(myfile).readlines()
The entire traceback:
Traceback (most recent call last):
File "/Users/my_name/PycharmProjects/MY_Project/Cross_validation.py", line 30, in <module>
data.append(k_fold(filename))
File "/Users/my_name/PycharmProjects/My_Project/Cross_validation.py", line 8, in k_fold
data = open(myfile).readlines()
IOError: [Errno 2] No such file or directory: 'nod_gyro_instance_11_P_4.csv'
My CSV files are such:
nod_gyro_instance_0_P_4.csv
nod_gyro_instance_0_P_3.csv
nod_gyro_instance_0_P_2.csv
nod_gyro_instance_0_P_5.csv
...
nod_gyro_instance_11_P_4.csv
nod_gyro_instance_10_P_6.csv
nod_gyro_instance_10_P_5.csv
nod_gyro_instance_10_P_4.csv
Why doesn't it recognize my nod_gyro_instance_10_P_4.csv file?
os.listdir returns just filenames, not absolute paths. If you're not currently in that same directory, trying to read the file will fail.
You need to join the dirname onto the filename returned:
data_dir = "/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro"
for filename in os.listdir(data_dir):
k_fold(os.path.join(data_dir, filename))
Alternatively, you could use glob to do both the listing (with full paths) and extension filtering:
import glob
for filename in glob.glob("/Users/my_name/PycharmProjects/My_Project/Data/Nod/Gyro/*.csv"):
k_fold(filename)

Renaming all the files in folders within directory

Basically I have got it all done. But when actually trying to rename the files I get the error
Traceback (most recent call last):
File
"C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav\sort_inner_wav.py", line 21, in <module>
os.rename(file, new_name)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Audio Track-10.wav' -> 'choman_10.wav'
Up until the last print statement the values are correct. Not sure how to rename it. Under wav folder there are 32 sub folder which has around 10 .wav files in it.
import os
rootdir = r'C:\Users\CHOMAN\Desktop\Earthquake_1_combine_3_jan\Earthquake_1_combine\wav'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
filepath = subdir+os.sep+file
if filepath.endswith('.wav'):
f_name, f_ext=(os.path.splitext(file))
if len(f_name) == 11:
f_name = f_name+'-0'
f_title,f_num =f_name.split('-')
f_num=f_num.zfill(2)
new_name = '{}_{}{}'.format('choman',f_num,f_ext)
print (file, new_name)
os.rename(file, new_name)
All you need is:
os.rename(filepath, subdir+os.sep+new_name)
That's because you need the full path.
If you are not running this script under the same location as 'rootdir' and there are sub directories, you need to specify the absolute path of source file and destination file. Otherwise, the file would not be found.
# python 2.7
os.rename(filepath, os.path.join(subdir, new_name))
# python >= 3.3
os.rename(file, new_name, subdir, subdir)

Renaming files recursively with Python

I have a large directory structure, each directory containing multiple sub-directories, multiple .mbox files, or both. I need to rename all the .mbox files to the respective file name without the extension e.g.
bar.mbox -> bar
foo.mbox -> foo
Here is the script I've written:
# !/usr/bin/python
import os, sys
def walktree(top, callback):
for path, dirs, files in os.walk(top):
for filename in files:
fullPath = os.path.join(path, filename)
callback(fullPath)
def renameFile(file):
if file.endswith('.mbox'):
fileName, fileExt = os.path.splitext(file)
print file, "->", fileName
os.rename(file,fileName)
if __name__ == '__main__':
walktree(sys.argv[1], renameFile)
When I run this using:
python walktrough.py "directory"
I get the error:
Traceback (most recent call last):
File "./walkthrough.py", line 18, in <module>
walktree(sys.argv[1], renameFile)
File "./walkthrough.py", line 9, in walktree
callback(fullPath)
File "./walkthrough.py", line 15, in renameFile
os.rename(file,fileName)
OSError: [Errno 21] Is a directory
This was solved by adding an extra conditional statement to test if the name the file was to be changed to, was a current directory.
If this was true, the filename to-be had an underscore added to.
Thanks to WKPlus for the hint on this.
BCvery1

Copy files in folder up one directory in python

I have a folder with a few files that I would like to copy one directory up (this folder also has some files that I don't want to copy). I know there is the os.chdir("..") command to move me to the directory. However, I'm not sure how to copy those files I need into this directory. Any help would be greatly appreciated.
UPDATE:
This is what I have now:
from shutil import copytree, ignore_patterns
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
I am getting the following error:
Traceback (most recent call last):
File "update.py", line 61, in <module>
copytree("/Users/aaron/Desktop/test/", "/Users/aaron/Desktop/", ignore=ignore_patterns('*.py', '*.txt'))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.py", line 146, in copytree
os.makedirs(dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/Users/aaron/Desktop/'
The shutil module can do this, specifically the copyfile, copy, copy2 and copytree functions. http://docs.python.org/library/shutil.html
You probably want something along these lines:
import os
import shutil
fileList = os.listdir('path/to/source_dir')
fileList = ['path/to/source_dir/'+filename for filename in fileList]
for f in fileList:
shutil.copy2(f, 'path/to/dest_dir/')
You can of course filter some file names out during the call to os.listdir(). For example,
fileList = [filename for filename in os.listdir('path/to/source_dir') if filename[-3] is '.txt']
instead of fileList = os.listdir('path/to/source_dir') to get just the .txt files

Categories

Resources