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.
Related
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"))
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)
Need a single function that will write a file if one does not exist.
Overwrite the file if it does exist, but saves the original or incriments the new file by 1.
Naming format is yyyymmdd, so if existing it would create a new file called yyymmdd-v2 or something like that.
This is what I have currently.
def write_diff_file(x):
from datetime import datetime
datestring = datetime.strftime(datetime.now(), '%Y_%m_%d')
try:
with open("./%s" % 'filediff_' + datestring + '.txt', 'a') as f:
line = str(x).replace("archive\\", "")
f.write(line)
f.write("\n")
f.name
#print "Comparison File Written"
except IOError as (errno, strerror):
print "I/O error({0}): {1}".format(errno, strerror)
print "Error in write_diff_file function"
You want to check whether the file exists and adapt the filename if it already does. Something like this should work:
import os
from datetime import datetime
datestring = datetime.strftime(datetime.now(), '%Y_%m_%d')
filename = 'filediff_' + datestring + '.txt'
filenb = 1
while os.path.exists(filename):
filenb += 1
filename = 'filediff_{0}_v{1}.txt'.format(datestring, filenb)
with open(filename, 'w') as f:
....
I have the current code for a sqlite db creation:
import storage
import os
import audiotools
def store_dir(d):
store = storage.HashStore()
for root, bar, files in os.walk(d):
for filename in files:
filename = root + '/' + filename
try:
store.store_file(filename)
print ("Stored %s% filename")
except audiotools.UnsupportedFile:
print ('Skipping unsupported file %s') % filename
except Exception, e:
print (e)
def main():
d = input('Enter the path to the music directory: ')
store_dir(d)
print ("Done.")
if __name__ == '__main__':
main()
When this code runs I get a syntax error msg. Please help !
Thanks in advance
There are a few things to address here.
First, this line:
print ('Skipping unsupported file %s') % filename
needs to be this:
print ('Skipping unsupported file %s' % filename)
Second, you need to use raw_input here:
d = input('Enter the path to the music directory: ')
which returns a string object, instead of input, which evaluates input as real Python code.
Third, your indentation is off. I'm pretty sure this is just a SO formatting error though.
Finally, you should use os.path.join here:
filename = root + '/' + filename
That isn't an error though, just a tip.
All in all, your code should look like this:
import storage
import os
import audiotools
def store_dir(d):
store = storage.HashStore()
for root, bar, files in os.walk(d):
for filename in files:
filename = os.path.join(root, filename)
try:
store.store_file(filename)
print ("Stored %s% filename")
except audiotools.UnsupportedFile:
print ('Skipping unsupported file %s' % filename)
except Exception, e:
print (e)
def main():
d = raw_input('Enter the path to the music directory: ')
store_dir(d)
print ("Done.")
if __name__ == '__main__':
main()