Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Python Error : read excel file(included xlsx, ...)

 An internal security tool caused a problem because xlsx was locked into a security program.
In conclusion, the following method was used, but it could not be solved.

error handling step...

code : occurred openpyxl error  

< zipfile.BadZipFile: File is not a zip file >


import openpyxl

 

if __name__ == "__main__" :

    wb = openpyxl.load_workbook("contents.xlsx")

    print(f"{wb}")

error

zipfile.BadZipFile: File is not a zip file


The following methods were used to solve this problem caused by in-house security tools.


step 1. encoding error 

< UnicodeDecodeError: 'cp949' codec can't decode byte 0xf0 in position 20: illegal multibyte sequence >


import openpyxl

import xlrd #add

if __name__ == "__main__" :

    file = open("contents.xlsx","r")

    wb = xlrd.open_workbook(file_contents=file.read()) #add

    print(f"wb")

 

error

wb = xlrd.open_workbook(file_contents=file.read())

UnicodeDecodeError: 'cp949' codec can't decode byte 0xf0 in position 20: illegal multibyte sequence



step 2. encoding error : add utf-8

< TypeError: an integer is required (got type str) >


import openpyxl

import xlrd

if __name__ == "__main__" :

    file = open("contents.xlsx","r", "utf-8")

    wb = xlrd.open_workbook(file_contents=file.read())

    print(f"wb")

 

error

file = open("contents.xlsx","r","utf-8")

TypeError: an integer is required (got type str)

must be specified Encoding type like "utf-8" as "python2 -> python3".



step 3. ???
< TypeError: an integer is required (got type str) >

import openpyxl

import xlrd

if __name__ == "__main__" :

    file = open("contents.xlsx","r", encoding="utf-8")

    wb = xlrd.open_workbook(file_contents=file.read())

    print(f"wb")

 

error

file = open("contents.xlsx","r", encoding="utf-8")

TypeError: an integer is required (got type str)

"utf-8-> encoding="utf-8"



It still hasn't been resolved.
Does anyone know how to read the Excel file that was locked due to the security tool?


#python error #read excel #openpyxl #zipfile.BadZipFile #encoding error

How to create qrc file(qml) in Python Qt(PyQt)

1. create qml file 
 - main.qml 
 - test.qml


2. create resource.qrc file
resource.qml code

-----------------------------------

<RCC>

<qresource>

    <file>qml/main.qml</file>

    <file>qml/test.qml</file>

</qresource>

</RCC>
-----------------------------------


3. execute command in terminal (in workspace included qml files)
 $ pyside2-rcc -o resource.py resource.qrc


4. check resource.py file 
 : 
Completed when the resource.py file is created.

 

 

How to use qrc file!

1. in main.py 

ex ) qrc:///filename

QUrl("qrc:///qml/test.qml")

 

2. in main.qml file

ex ) qrc:/qml/test.qml

source: "qrc:/qml/test.qml"


#qrc #resource.qrc #resource.py #python #qt #pyqt #pyside2-rcc


Python error : pip installer ssl

solve :


pip install [item] --trusted-host pypi.org --trusted-host files.pythonhosted.org

ex)

$ pip install requests --trusted-host pypi.org --trusted-host files.pythonhosted.org
$ pip install psutil --trusted-host pypi.org --trusted-host files.pythonhosted.org
$ pip install --upgrade paramiko --trusted-host pypi.org --trusted-host files.pythonhosted.org
$ pip install --upgrade scp --trusted-host pypi.org --trusted-host files.pythonhosted.org


#python #pip #pip3 #error #--trusted-host #pypi.org #pythonhosted #ssl

Python logging module (write log file) / basicConfig does not create log file issue(solved)

Python

logging module : write log file for exec. log in python(i think)

issue :

If "fullpath = variable + filename" as shown above, there is an issue(not create a log file).
The cause is unknown, but if " fullpath = "./log/test.log" " directly, you can see that the file is normally generated.


example 1 and issue of example 1,  solved: example 2


example 1.

import logging

def writeLogFile(logText):
    mypath = "./log"
    fullpath = mypath + "/test.log"    #mypath = "./log"
    logging.basicConfig(filename = fullpath, level=logging.DEBUG)
    logging.debug(logText)

If "fullpath = variable + filename" as shown above, there is an issue(not create a log file).

The cause is unknown, but if " fullpath = "./log/test.log" " directly, you can see that the file is normally generated.

For the above problem, I don't use basicConfig, So, I use it with example 2.


example 2 and solve.

import logging
import logging.handlers

log : ""

def initLog():
    global log
    mypath = "./log"
    fullpath = mypath + "/test.log"    #mypath = "./log"

    log = logging.getLogger('my_log')
    log.setLevel(logging.DEBUG)
    fileHandler = logging.FileHandler(fullpath)
    log.addHandler(fileHandler)


def writeLogFile(logText):
    log.debug(logText)

As shown above, log can be created as a file without any problems.


#python #logging #log #logfile #basicConfig #issue #solve #logginghandler


Python Lotto example (Get 6 numbers randomly)

Python Lotto example (Get 6 numbers randomly)


This extracts N numbers randomly from a value of 1-45.
Arrange the six most frequently produced numbers in ascending order.

To run .exe immediately, create "count.txt" with the exe file and run. (Write the number of times to perform in count.txt.):

When running as PowerShell or cmd, do as follows.

arg 1 : Number of random extractions
arg 2: How many sets of six will be created?

./lotto.exe N Loop
ex) ./lotto.exe 10000 4
the numbers 1-45, It randomly spins 10000 times to pick the six frequently produced numbers, and then it repeats them four times to extract four sets.

Ex)
./lotto.exe 10000
./lotto.exe 10000 5




count.txt
10000


lotto.py
import sys
import os
import random
#DEFAULT_PROJECT_FILE_PATH = "./data"
MAX_COUNT = 10000000
DEFAULT_COUNT = 1000000
MIN_COUNT = 1
def Print(*args): 
    func_name = "[" + sys._getframe(1).f_code.co_name + "] "
    for value in args:
        if type(value) is str:
            func_name = func_name + value
        else:
            func_name = func_name + str(value)
    
    print(func_name)
class FileReadWriteClass :
    def __init__(selfparent=None):
        pass
    
    def readFile(selfpath):   # only 1 line
        # writedata.py
        fp = open(path, mode='rt'encoding='utf-8')
        data = fp.read()
        fp.close()
        return data
    def writeFile(selfpathdata):
        fp = open(path, 'a+')
        fp.write(data)
        fp.write("\n")
        fp.close()

class CalculatorClass :
    calculatedNumbers = []
    
    def __init__(selfparent=None):
        pass
    
    def calculator(selfcount) :
        numberDict = {}
        index = 0
        while index < count:
            index += 1
            num = random.randint(145)
            if num in numberDict:
                numberDict[num] += 1
            else:
                numberDict[num] = 0
        sixValues = sorted(numberDict.items(), reverse=Truekey=lambda item: item[1])
        index = 0
        data = []
        #print(sixValues)
        for key in sixValues:
            Print(key)
            #print(key[0])
            data.insert(index, key[0])
            if index >= 5:
                break
            else:
                index += 1
        data.sort()
        self.calculatedNumbers = data
        return self.calculatedNumbers
    def getValues(self) :
        return self.calculatedNumbers

def main(value = Noneloop = 1):
    Print("Main")
    calClass = CalculatorClass()
    fileRWClass = FileReadWriteClass()
    index = 0
    while index < int(loop) :
        if value is None :
            count = fileRWClass.readFile("./count.txt")
        else :
            count = value
        calClass.calculator(int(count))
        result = calClass.getValues()
        Print(count, " :: "str(result))
        fileRWClass.writeFile("./result.txt", count + " :: " + str(result))
        index += 1
    Print("Close")
if __name__ ==  "__main__"
    if (len(sys.argv) <= 1) :
        main()
    elif (len(sys.argv) == 2) :
        main(sys.argv[1])
    elif (len(sys.argv) == 3) :
        main(sys.argv[1], sys.argv[2])
    else:

        Print("Error")


create exe file
> pyinstaller lotto.py --onefile


#python #lotto #random number #example

Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore!

 🏙️ Apartment Buying Guide 2025: Shocking Red Flags You Should NEVER Ignore! 🚨 Are you thinking about buying an apartment in 2025? 🏢  It’...