Write and Save As with python in plugin QGIS - python

I try to make plugin in QGIS and i want to make save as button but i got error message like this
Traceback (most recent call last):
File "C:\Users\Mr.Pakde/.qgis2/python/plugins\latih\latihdialog.py", line 69, in
saveAs
if not filename.isEmpty():
AttributeError: 'unicode' object has no attribute 'isEmpty'
I write my code like this :
cariButton = self.ui.btnCari
QtCore.QObject.connect(cariButton,QtCore.SIGNAL('clicked()'),self.cari)
saveButton = self.ui.btnSave
QtCore.QObject.connect(saveButton, QtCore.SIGNAL('clicked()'),self.saveAs)
def cari(self, event=None):
#open dialog
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')
self.ui.lineFile.setText(filename)
#panggil isi data
self.isiDataFile(filename)
def isiDataFile(self, nmfile):
#buka dengan open mode baca
teksFile = open(nmfile, 'r').read()
self.ui.textFile.setText(teksFile)
def _save(self, filename):
f = open( filename, "w" )
f.write( "%s" % self.lineFile.text() )
f.close()
def savefile(self):
if self.filename:
self._save( "%s" % self.filename )
else:
self.saveAs()
def saveAs(self):
filename = QtGui.QFileDialog(self).getSaveFileName()
if not filename.isEmpty():
_filename = "%s" % filename
self._save( _filename )
self.setFilename( _filename )
I try to save file in different format

The error message tells you exactly what the problem is:
filename = QtGui.QFileDialog(self).getSaveFileName()
if not filename.isEmpty():
filename is a unicode object, which doesn't have an isEmpty() method. Try:
if filename != "":
or, as empty strings are False-y:
if filename:

Related

Error while creating a saveAS function in Python due to [Errno 22]

I'm creating a simple text editor in Python using tkinter.
When I try to create a SaveAs function I get this error:
File "c:\Users\hp\Desktop\Parcial II - Compiladores\NotePad_DS.py", line 65, in save_file
file = open(file, 'w')
OSError: [Errno 22] Invalid argument: '\n'
This is my code:
def save_file():
global text_field
file = text_field.get(1.0, END)
if file == '':
file = None
else:
#This is the line 65 where the editor says there is an error----
file = open(file, 'w')
#-------
file.write(text_field.get(1.0, END))
file.close()
if file is None:
file = fd.asksaveasfilename(initialfile='Untitled.txt', defaultextension='.txt',
filetypes=[("Text File", "*.txt*"), ("Word Document", '*,docx*'), ("PDF", "*.pdf*")])
else:
file = open(file, 'w')
file.write(text_field.get(1.0, END))
file.close()
root.title(f"{os.path.basename(file)} - NotepadDS")

Cannot delete file with send2trash

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"))

cannot open file named directory path + filename + current date and time

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.

Save As error 'X' object has no attribute 'Y' in QGIS plugin

I try to make plugin to open, read and then save save in different format, i open .xml file and try to save as / write it in text or pdf format, but i get error message like this :
File "C:\Users\Mr.Pakde/.qgis2/python/plugins\latih\latihdialog.py", line 71, in saveAs
self._save( _filename )
File "C:\Users\Mr.Pakde/.qgis2/python/plugins\latih\latihdialog.py", line 59, in _save
f.write( "%s" % self.nmfile.text() )
AttributeError: 'latihDialog' object has no attribute 'nmfile'
This is my code
cariButton = self.ui.btnCari
QtCore.QObject.connect(cariButton, QtCore.SIGNAL('clicked()'),self.cari)
saveButton = self.ui.btnSave
QtCore.QObject.connect(saveButton, QtCore.SIGNAL('clicked()'),self.saveAs)
def cari(self, event=None):
#open dialog
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', '*.xml')
self.ui.lineFile.setText(filename)
#panggil isi data
self.isiDataFile(filename)
def isiDataFile(self, nmfile):
#buka dengan open mode baca
teksFile = open(nmfile, 'r').read()
self.ui.textFile.setText(teksFile)
def _save(self, simpan):
f = open( simpan, "w" )
f.write( "%s" % self.nmfile.text() )
f.close()
def savefile(self):
if self.simpan:
self._save( "%s" % self.simpan )
else:
self.saveAs()
def saveAs(self):
tulis = QtGui.QFileDialog(self).getSaveFileName()
if tulis !="":
_filename = "%s" % tulis
self._save( _filename )
self.setFilename( _filename )
You are trying to use the variable nmfile as a instance variable by addressing it in the way self.nmfile. However, this variable/attribute has never been initialized (compare: AttributeError: 'latihDialog' object has no attribute 'nmfile').
You use the variable in a local context in isiDataFile, but as soon as this method ends, the local variable is lost and cannot be accessed any more.
You have to design the flow of your code, that it either will
Assign this instance variable, before the _save-method is called ( e.g. self.nmfile = '/tmp/myfile' )
Pass an argument nmfile to the _save-method, so it will be available there

Cannot open file using my text editor in wxpython?

The text editor in wxpython cannot open saved files. The files are saved as text files but while opening the the following error appears
Error opening file
'charmap' codec can't decode byte 0x8d in position 5: charcter maps to <undefined>
The code used for opening the file is given below,
def DoOpenFile(self):
#wcd = 'All files (*)|*|Editor files (*.ef)|*.ef|'
wcd='Text files(*.txt)|*.txt|Plain Text files (*.txt)|*.txt'
dir = os.getcwd()
open_dlg = wx.FileDialog(self, message='Choose a file', defaultDir=dir, defaultFile='',
wildcard=wcd, style=wx.OPEN|wx.CHANGE_DIR)
if open_dlg.ShowModal() == wx.ID_OK:
path = open_dlg.GetPath()
try:
file = open(path, 'r')
text = file.read()
file.close()
if self.text.GetLastPosition():
self.text.Clear()
self.text.WriteText(text)
self.last_name_saved = path
self.statusbar.SetStatusText('', 1)
self.modify = False
self.SetTitle(window_title + path)
except IOError, error:
dlg = wx.MessageDialog(self, 'Error opening file' + str(error))
dlg.ShowModal()
except UnicodeDecodeError, error:
dlg = wx.MessageDialog(self, 'Error opening file\n' + str(error))
dlg.ShowModal()
open_dlg.Destroy()
Change your code as
file = codecs.open(path, 'r',encoding='utf-8')

Categories