import PyPDF2, os, sys, send2trash,pathlib
def encrypt(filename, password):
with open(filename, "rb") as readfile:
reader = PyPDF2.PdfFileReader(readfile)
writer = PyPDF2.PdfFileWriter()
if not reader.isEncrypted:
for page in range(reader.numPages):
writer.addPage(reader.getPage(page))
else:
print(f"{filename} is encrypted")
return None
with open(f"{filename.split('.')[0]}_encrypted.pdf", "wb") as writefile:
writer.encrypt(password)
try:
writer.write(writefile)
except OSError as e:
print(f"File write error {e}")
return None
with open(f"{pathlib.Path(filename).parent}\{pathlib.Path(filename).stem}_encrypted.pdf", "rb") as checkfile:
result = PyPDF2.PdfFileReader(checkfile).decrypt(password)
if result != 0:
try:
send2trash.send2trash(filename)
print(f"file {filename} was deleted after encrypted file verification")
return "Done"
except OSError as e:
print(f"Delete error: {e}, filename: {filename}")
else:
print("Encrypted file %s was not verified so original file %s was not deleted" % (f"{filename.split('.')[0]}_encrypted.pdf", filename))
return None
def decrypt(filename, password):
with open(filename, "rb") as readfile:
reader = PyPDF2.PdfFileReader(readfile)
writer = PyPDF2.PdfFileWriter()
if not reader.isEncrypted:
print(f"{filename} is not_encrypted")
return None
else:
result = reader.decrypt(password)
if result == 0:
print(f"{filename} was not decrypted with password: {password}")
return None
else:
for page in range(reader.numPages):
writer.addPage(reader.getPage(page))
try:
with open(f"{filename}_decrypted.pdf", "wb") as writefile:
writer.write(writefile)
except OSError as e:
print(f"File write error {e}")
return None
return "Done"
# password = sys.argv[1]
# option = sys.argv[2]
password = "test"
option = "decrypt"
if option not in ["encrypt", "decrypt"]:
sys.exit(f"Wrong option, option provided is {option}, supposed to be encrypt or decrypt")
folder_path = os.path.abspath(input("Please enter the path"))
if os.path.exists(folder_path):
for folder, subfolders, files in os.walk(folder_path):
pdfs = filter(lambda x: str(x).lower().endswith(".pdf"), files)
for file in pdfs:
filename = os.path.join(folder, file)
reader = PyPDF2.PdfFileReader(open(filename, "rb"))
encrypt(filename, password) if option == "encrypt" else decrypt(filename, password)
else:
print(f"{folder_path} doesnt exist, exiting")
sys.exit(f"{folder_path} not found")
Hello! The code above doesnt delete the .pdf files with send2trash.
Files seems to be closed, if i copy encrypt function to another file and run it separately - it delete the file provided - no problem. But in this script i get [win32] None errors - it just refuse to delete any file.
Can anyone kindly point at the point i'm missing? Thanks alot !
PS It supposed to go through folder(subfolders), look for .pdf files and encrypt/decrypt them.
Found the issue, sorry :P
reader = PyPDF2.PdfFileReader(open(filename, "rb"))
Related
So right now my code only writes out if the given searchword is in the folder or not. But I would like it to also write out the filenames where the given word exists. How would it be done?
import os
folder = input("Enter the search path to the folder: ")
search_word = input("Enter the search word: ")
os.chdir(folder)
def read_files(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read().lower()
return contents
except FileNotFoundError:
print("File couldn't be found!")
except IOError:
print("Couldn't read from file")
except:
print("An error has occurred")
def write_searches():
try:
with open("ord.txt", 'w') as file:
file.write(folder+ ": " + search_word +"\n")
if search_word not in read_files(file_path):
file.write("The word isn't in the folder!")
else:
file.write("The word is in the file!")
except Exception:
print("Couldn't write to file!")
print("These are the following files that have been searched: ")
for file in os.listdir():
if file.endswith(".txt"):
file_path = f"{folder}\{file}"
print("\t",file_path)
read_files(file_path)
if __name__ == "__main__":
write_searches()
Change:
file.write("The word is in the file!")
to:
file.write(f"The word is in the file {file_path}!")
Note that as written, write_searches doesn't actually iterate over multiple files; you're doing that in a different loop. I think this might be more along the lines of what you're trying to do:
import os
def search_file(file_path: str, search_word: str) -> bool:
try:
with open(file_path, 'r', encoding='utf-8') as file:
contents = file.read().lower()
return search_word.lower() in contents
except Exception as e:
print(f"Failed to read from {file_path}: {e}")
return False
def write_searches() -> None:
folder = input("Enter the search path to the folder: ")
search_word = input("Enter the search word: ")
os.chdir(folder)
try:
with open("ord.txt", 'w') as output:
output.write(f"{folder}: {search_word}\n")
print("These are the following files that have been searched: ")
for file in os.listdir():
if not file.endswith(".txt"):
continue
file_path = os.path.join(folder, file)
if search_file(file_path, search_word):
output.write(f"The word is in {file}!\n")
else:
output.write(f"The word isn't in {file}!\n")
print("\t", file_path)
except Exception as e:
print("Couldn't write to file! {e}")
if __name__ == "__main__":
write_searches()
This code always goes into the except section
to_add = "text to add"
try:
with open ('text.txt','r') as txt:
txt.write('text to add'+to_add')
print("done")
except:
to_add== 0 or None or ''
print("unable to write to file")
Open file as 'w' not 'r'
with open('test.txt', 'w') as txt:
There are a couple fixes required.
try with this snippet:
to_add = "text to add"
try:
with open ('text.txt', 'w') as txt: # change the mode to write
txt.write('text to add' + to_add) # removing the last char '
print("done")
except NameError:
print("unable to write to file")
I want to create a function, user_dialogue() that asks for the name of two files. This function needs to handle Errors such as IOError. The two files should then run through another function I created, that is called encryption_function.
The program should work like this:
Name of new encrypted file: out_file.txt
Name of file to be encrypted:blah.txt
That resulted in an error! Please try again.
Name of file to be encrypted: my file.csv
Encryption completed!
This is my code so far:
def user_dialogue():
file1 = open(input("New name of file: "), 'w')
done = False
while not done:
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
except IOError as error:
print("File doesn't exist! The error is of the type: ", error)
else:
file2.close()
done = True
encrypt_file(file2,file1)
user_dialogue()
And this is my function encrypt_file:
def encrypt_file(in_file, out_file):
fr = open(in_file, 'r')
fileread = fr.read()
encryptedfile = text_encryption_function.encrypt(fileread)
fr.close()
fw = open(out_file, 'a+')
fw.write(encryptedfile)
fw.close()
return in_file, out_file
For some reason the code doesn't work! Any help please?
Using context manager with:
def user_dialogue():
try:
with open(input("Name of file that you want to encrypt: "), 'r') as file2:
try:
with open(input("New name of file(encrypted): "), 'w') as file1:
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)
Using try/except:
def user_dialogue():
try:
file2 = open(input("Name of file that you want to encrypt: "), 'r')
try:
file1 = open(input("New name of file(encrypted): "), 'w')
encrypt_file(file2, file1)
except IOError as e3:
print('No access')
else:
file1.close()
except FileNotFoundError as e1:
print('No such file')
except IOError as e2:
print('No access')
else:
file2.close()
def encrypt_file(in_file, out_file):
fileread = in_file.read()
encryptedfile = text_encryption_function.encrypt(fileread)
out_file.write(encryptedfile)
In book headfirstpython in chapter4 they have used the syntax
print(list_name, file= output_file_name)
For them it's working fine, but for me it's giving syntax error on file = output_file_name. The python version is same i.e. 3.
code:
import os
man = []
other = []
try:
data = open('sketch.txt')
for each_line in data:
try:
(role, line_spoken) = each_line.split(':', 1)
line_spoken = line_spoken.strip()
if role == 'Man':
man.append(line_spoken)
elif role == 'Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print('The datafile is missing!')
try:
man_file = open('man_data.txt', 'w')
other_file = open('other_data.txt', 'w')
print(man, file=man_file)
print(other, file=other_file)
except IOError:
print('File error.')
finally:
man_file.close()
other_file.close()
As per the help of print function indicates
file: a file-like object (stream); defaults to the current
sys.stdout.
So the input is not supposed to be file-name but rather a file-like object. If you want to write into (say) a text file, you need to first open it for writing and use the file handle.
f = open("output.txt",'w')
print(list_name, file=f)
I created a txt file named as directory path+current date and time. The following error occurs:
File cannot be opened. coercing to Unicode: need string or buffer,
NoneType found
def create_file(count):
filename = "countMetrics"
dir = os.getcwd()
#print 'Current directory path is-'
#print dirPath
date = datetime.datetime.now()
now = date.strftime("%Y-%m-%d %H:%M")
#print 'current date and time is-'
#print now
## date and time representation
#print "Current date & time " + time.strftime("%c")
dirPath = os.path.join(dir, filename)
filenameCreated = dirPath+now+".txt"
#filenameCreated = dirPath+filename+now+".txt"
print filenameCreated
f = openfile(filenameCreated,'a')
return f
#writeFile(f,count)
#defining openfunction
def openfile(filename,mode):
try:
open(filename,mode)
except Exception, err:
print("File cannot be opened.")
print(str(err))
return
def readFile(filename):
try:
target = open(filename,'r')
content=filename.read() # reading contents of file
for line in target:
print content
target.close()
except:
print "File is empty.."
return
#defining write function
def writeFile(filename,count):
try:
target = openfile(filename,'a')
target.write(count)
target.close()
except Exception, err:
print("File have no data to be written.")
print(str(err))
return
Your openfile function is not returning anything. Change it to return the open file descriptor and your code might work :-)
def openfile(filename, mode):
try:
return open(filename, mode)
except Exception as err:
print "File cannot be created", err
return
And add an if in the main code to check whether you receive file descriptor.
f = openfile(filenameCreated,'a')
if not f:
print "No file created"
return
return f
And your writeFile function will be like this:
def writeFile(target, count):
try:
target.write(count)
target.close()
return 1
except Exception as err:
print "Cannot write into the file"
return 0
Because your openfile itself returns a descriptor. You don't need to create another one.