Cannot open file using my text editor in wxpython? - python

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

Related

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

Encrypting a file using saved RSA keys in python

I am trying to encrypt an image file using RSA keys that are generated by another script and saved into a .pem file. when i am trying to encrypt the file its showing errors like this
Traceback (most recent call last):
File "rsaencrypt.py", line 85, in <module>
main()
File "rsaencrypt.py", line 45, in main
content = fileObj.read()
File "/usr/lib64/python3.7/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
I am new to python and file handling so i think the problem is in the way of how i am handling the files both the key files and the inputfile. Looking forward to some suggestion.
Heres the code of my encryption file:
import time, os, sys
def main():
inputFilename = 'img.jpg'
# BE CAREFUL! If a file with the outputFilename name already exists,
# this program will overwrite that file.
outputFilename = 'encrypted.jpg'
myKey = open("public_key.pem",'r')
myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
# If the input file does not exist, then the program terminates early.
if not os.path.exists(inputFilename):
print('The file %s does not exist. Quitting...' % (inputFilename))
sys.exit()
# If the output file already exists, give the user a chance to quit.
if os.path.exists(outputFilename):
print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename))
response = input('> ')
if not response.lower().startswith('c'):
sys.exit()
# Read in the message from the input file
fileObj = open(inputFilename)
content = fileObj.read()
fileObj.close()
print('%sing...' % (myMode.title()))
# Measure how long the encryption/decryption takes.
startTime = time.time()
if myMode == 'encrypt':
translated = transpositionEncrypt.encryptMessage(myKey, content)
elif myMode == 'decrypt':
translated = transpositionDecrypt.decryptMessage(myKey, content)
totalTime = round(time.time() - startTime, 2)
print('%sion time: %s seconds' % (myMode.title(), totalTime))
# Write out the translated message to the output file.
outputFileObj = open(outputFilename, 'w')
outputFileObj.write(translated)
outputFileObj.close()
print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content)))
print('%sed file is %s.' % (myMode.title(), outputFilename))
# If transpositionCipherFile.py is run (instead of imported as a module)
# call the main() function.
if __name__ == '__main__':
main()
You need to open the file in binary mode, not text (which is the default).
Turn
fileObj = open(inputFilename)
into
fileObj = open(inputFilename, "rb")
and .read() will return bytes (i.e. binary data), not str (i.e. text).

Encoding issues while saving json to file

I am reading logs from mobile device, from system terminal line by line and saving it to string.
Then I cut this string into parts and want to generate .*json file from it.
I have my .*json in form of dictionary and I want to save it to file with usage of this custom made method:
def save_json_to_file(json_dict, folder, file_name, extension):
directory = add_ending_slash(GlobalConfig.OUTPUT_DIR) + add_ending_slash(str(folder))
file_path = clean_path(directory + str(file_name) + "." + extension)
output_file = None
try:
if not os.path.exists(directory):
os.makedirs(directory)
output_file = open(file_path, "w")
absolute_path = os.path.abspath(file_path)
Printer.system_message(TAG, "Created json file '" + absolute_path + "'.")
json.dump(json_dict, output_file, indent=4, ensure_ascii=False)
except Exception as e:
message = "Unable to create file '{}.{}'. Error message: {}"
message = message.format(file_path, extension, str(e))
raise LauncherFlowInterruptedException(TAG, message)
finally:
if output_file is not None and hasattr(output_file, "close"):
output_file.close()
return absolute_path
At some point of json.dump doing it's job I get crash:
File "/Users/F1sherKK/anaconda3/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 89: invalid start byte
I tried changing every string I receive from console by doing:
received_terminal_line = received_terminal_line.encode('utf-8')
I know that in incoming strings there can be various different encodings, in example emoji.

pyCURL download and get content from mp3 file

I'm trying to get content from downloaded file. If i save file like .mp3 it even playing. But when i get content there are a lot of "terrible" characters i.e. (û dInfo.ð"""".....::::EEEEEQQQQ]]]]]hhhhttttt¢¢¢¢®®®®®ººººÅÅÅÅÅÑÑÑÑÝÝÝÝÝèèèèôôôôôÿÿÿÿ:LAME3.96r´.l4 $N .ð]Ú5ÿû d Ô|c½i4BGçá"ʹU§ a0pTìÌ xà0 +£â?=yÃkðý§ýÛußAfØÿ®ÙBDgøQÊ0£a=¹ OTG# )É ÄN¨hÎDMWQÛ0wmrÛA MdCeÞ9:!b>¢~Ú½´&ÞýÛ/¿h­·{þ>Åï²{·w±Ä,ÅõtewßS©?Ï'è! p#lHåÀ1üoù!c Aæø?Íæ0#äzôüÿsì§òp}o¾Ðn¨:Ð À#1®-0¦ ÐËÛþÐ褹À~! êõCÄâr+Ççú!ɱA3uå^O¦I÷'ív(µ~ÉNÎ~8æÙøÕ+Xy¬gt}êÑ3xk¿½ÞZ÷]ë^ÖÅ¢}åýíªn¾?µ)_{×ÇÎÿÝ>ÿzÞ>wÿß¾5﬿»ü}z}kDtwk)Ó=Ú[ÿzfXÞµ%q Gŧ~(°Ë%¬ÇºJùÝÇá3JBĸÑâ·Ê!W²qll°¡WÎÚRÕ¨âU0BD$F$ÅÕÀèûÏ*©l^Î¥¢3ëÿû¢d¬LY~s`AJ#Á%ù­ 4¨ËÍ;3sB½²ý»é¨murz{S0Ühà #Qö0Â(ÚFíê9(øi¸ò½¸~äÌ]ï¼a b°±±§Rióÿ÷·±O?Ã?:3£M20 /ÿÿÿçßîzöDIþï_ÿÿÿÿú±c>a¾¨2e ÁÙ£¯ÿÿÿÿÿýþÿÿÿÿ ![]h1EOFðKçYwA%ÜSԾó":9Ç5 RþèvC?7òEWÔ´üJdzcKÿÿTdp Lï¬DÆØ£Rm7£Ww·´ÅUeé¢hÇRî÷ #\uä«À#¿6òXµËÖÿ+U Oó}å-) This my code:
fp = open('audio.txt', "wb")
ch = curl.Curl()
ch.setopt(curl.URL, url)
ch.setopt(curl.TRANSFERTEXT, True)
ch.setopt(curl.AUTOREFERER, True)
ch.setopt(curl.FOLLOWLOCATION, True)
ch.setopt(curl.POST, False)
ch.setopt(curl.HTTPHEADER, ['REMOTE_ADDR:' + self.ip, 'HTTP_X_FORWARDED_FOR:' + self.ip])
ch.setopt(curl.USERAGENT, self.useragent)
ch.setopt(curl.CONNECTTIMEOUT, self.connect_timeout)
ch.setopt(curl.TIMEOUT, self.curl_timeout)
ch.setopt(curl.SSL_VERIFYPEER, False)
ch.setopt(curl.COOKIE, "JSESSIONID=" + sessionid)
ch.setopt(curl.WRITEDATA, fp)
try:
result = ch.perform()
except curl.error as error:
#errno, errstr = error
ch.close()
return 'Ошибка считывания mp3 файла с сервиса ФМС.'
fp.close()
with open('audio.txt', 'r', encoding = "ISO-8859-1") as content_file:
content_file.seek(0)
content = content_file.read()
return content
How I can get normal characters (in UTF8) ? thanks.
try to remove ch.setopt(curl.TRANSFERTEXT, True), cause mp3 is binary.
After that change fp = open('audio.txt', "wb") to fp = open('audio.mp3', "wb")
now you'll have correct mp3 saved on disk.
Then try use following
import mp3play
filename = r'audio.mp3'
mp3 = mp3play.load(filename)
mp3.play()
you should have installed mp3play package.

Write and Save As with python in plugin QGIS

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:

Categories