Cannot open file in subdirectory with ZipFile - python

For whatever reason i cannot open or access the file in this subdirectory. I need to be able to open and read files within subdirectories of a zipped folder. Here is my code.
import zipfile
import os
for root, dirs, files in os.walk('Z:\\STAR'):
for name in files:
if '.zip' in name:
try:
zipt=zipfile.ZipFile(os.path.join(root,name),'r')
dirlist=zipfile.ZipFile.namelist(zipt)
for item in dirlist:
if 'Usb' in item:
input(item)
with zipt.open(item,'r') as f:
a=f.readlines()
input(a[0])
else:pass
except Exception as e:
print('passed trc file {}{} because of {}'.format(root,name,e))
else:pass
This code currently gives me the error:
File "StarMe_tracer2.py", line 133, in tracer
if 'er99' in line:
TypeError: a bytes-like object is required, not 'str'

The content read from the file object opened with ZipFile.open is bytes rather than a string, so testing if a string 'er99' is in a line of bytes would fail with a TypeError.
Instead, you can either decode the line before you test:
if 'er99' in line.decode():
or convert the bytes stream to a text stream with io.TextIOWrapper:
import io
...
with io.TextIOWrapper(zipt.open(item,'r'), encoding='utf-8') as f:

Related

decode every file in a zip file with python

I have a zip file file link
it is encoded with utf-8 code, how can I decode every file within it? I tried but failed: TypeError: decoding with 'utf-8' codec failed (TypeError: a bytes-like object is required, not 'ZipFile')
from zipfile import ZipFile
import codecs
with ZipFile('articles.zip', 'r') as zip:
with zip.open('articles/document0001.txt') as file:
codecs.decode(file, encoding='utf-8', errors='strict')
also there are 100 files on that Zip, any smart way to do the decoding for all the files in one off?
You can use bytes.decode on the text:
from zipfile import ZipFile
with ZipFile('articles.zip', 'r') as z:
with z.open('articles/document0001.txt') as file:
file_text = file.read().decode('utf-8')
print(file_text) # or do whatever else you want to do with it.

Looping through Base64 txt files for bulk conversion to images?

I have a large number of txt files that contain the base64 encoding for image files. Each txt file has a single encoding line starting with "data:image/jpeg;base64,/9j/.........". I got the following to work as far as saving the image:
import base64
import os
import fnmatch
os.chdir(r'D:\Users\dubs\slidesets'):)
with open('data.image.jpeg.0bac61939da0c.txt', 'r') as file:
str = file.read().replace('data:image/jpeg;base64,', '')
print str
picname = open("data.image.jpeg.0bac61939da0c.jpg", "wb")
picname.write(str.decode('base64'))
picname.close()
My end goal would be to look in a directory for any txt file with "jpeg" in the name, get and edit the string from it, change to image, and save the image in the same directory with the same filename ('data.image.jpeg.0bff54917a8c7.txt' to 'data.image.jpeg.0bff54917a8c7.jpg').
import fnmatch
import os
import base64
os.chdir(r'D:\Users\dubs\slidesets')
for file in os.listdir(r'D:\Users\dubs\slidesets')
if fnmatch.fnmatch(file, "*jpeg*.txt"):
newname = os.path.basename(file).replace(".txt", ".jpg")
with open(file, 'r') as file:
str = file.read().replace('data:image/jpeg;base64,', '')
picname = open("newname", "wb")
picname.write(str.decode('base64'))
picname.close()
The error that I am getting:
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
AttributeError: 'str' object has no attribute 'decode'
I tried "newname" 'newname' and newname because I was unsure how that works with a variable instead, but that didn't help. Not sure why it works for one file in my top code but not in the loop?

FTP Upload--ASCII mode--a bytes-like object is required, not 'str'

I'm trying to write a FTP upload program for text files. However I'm getting this error:
builtins.TypeError: a bytes-like object is required, not 'str'.
I am using Python 3.6.
Here is my code:
def _upload_to_ftp(self, ftp_handle, name):
# upload a single file to ftp directory
with open(name,'r') as f:
print("uploading"+name)
filename = os.path.basename(name)
ftp_handle.storlines('STOR %s' %filename, f)
I could not figure out why.
Unfortunately, what FTP calls text is still bytes for Python 3. Python 3 strings use Unicode characters that need to be encoded to bytes in order to be written to files and FTP deals with files. But here it is even simpler: you have just to open the local file in binary mode to have it deliver bytes instead of strings:
def _upload_to_ftp(self, ftp_handle, name):
# upload a single file to ftp directory
with open(name,'rb') as f: # use binary mode for file
print("uploading"+name)
filename = os.path.basename(name)
ftp_handle.storlines('STOR %s' %filename, f)

Opening a video file from local drive as buffer and write it into new file

I have multiple broken video files of one same video I need to join them together as one video again but when I tried this
import os
path = 'C:/temp/test'
files = os.listdir(path)
for file in files:
mainFile = open('C:/temp/main.mp4','ab')
with open(path+'/'+file,'rb') as read:
print (read)
mainFile.write(read)
mainFile.close()
It threw an Error saying
TypeError: must be string or buffer, not file
So I don't know how do I make a video file buffer. I tried googling it and I found something called ffmpeg but it's a third party app. All I need is buffer of a file.
Note that open() returns a file object rather than the content of the file. The error occurs because a file object is being passed into write().
You can call read() method of a file object to read and return the content of the file.
Try
import os
path = 'C:/temp/test'
files = os.listdir(path)
for file in files:
mainFile = open('C:/temp/main.mp4','ab')
with open(path+'/'+file,'rb') as f:
mainFile.write(f.read())
mainFile.close()

Send file contents over ftp python

I have this Python Script
import os
import random
import ftplib
from tkinter import Tk
# now, we will grab all Windows clipboard data, and put to var
clipboard = Tk().clipboard_get()
# print(clipboard)
# this feature will only work if a string is in the clipboard. not files.
# so if "hello, world" is copied to the clipboard, then it would work. however, if the target has copied a file or something
# then it would come back an error, and the rest of the script would come back false (therefore shutdown)
random_num = random.randrange(100, 1000, 2)
random_num_2 = random.randrange(1, 9999, 5)
filename = "capture_clip" + str(random_num) + str(random_num_2) + ".txt"
file = open(filename, 'w') # clears file, or create if not exist
file.write(clipboard) # write all contents of var "foo" to file
file.close() # close file after printing
# let's send this file over ftp
session = ftplib.FTP('ftp.example.com','ftp_user','ftp_password')
session.cwd('//logs//') # move to correct directory
f = open(filename, 'r')
session.storbinary('STOR ' + filename, f)
f.close()
session.quit()
The file will send the contents created by the Python script (under variable "filename" eg: "capture_clip5704061.txt") to my FTP Server, though the contents of the file on the local system do not equal the file on the FTP server. As you can see, I use the ftplib module. Here is my error:
Traceback (most recent call last):
File "script.py", line 33, in<module>
session.storbinary('STOR ' + filename, f)
File "C:\Users\willi\AppData\Local\Programs\Python\Python36\lib\ftplib.py", line 507, in storbinary
conn.sendall(buf)
TypeError: a bytes-like object is required, not 'str'
Your library expects the file to be open in binary mode, it appears. Try the following:
f = open(filename, 'rb')
This ensures that the data read from the file is a bytes object rather than str (for text).

Categories