⬅️ **[[$-Tools|Tools]]**
***
# Python Scripting
- w3schools: https://www.w3schools.com/python/default.asp
- https://docs.python.org/3.7/tutorial/index.html
- https://www.tutorialspoint.com/python/string_startswith.htm
- https://automatetheboringstuff.com/
- Using Directories: https://www.askpython.com/python/examples/list-files-in-a-directory-using-python
## 2024-11 error: externally-managed-environment
- https://pimylifeup.com/python-externally-managed-environment/
- Lösung: `python3 -m pip config set global.break-system-packages true`
## GUI Frameworks
- [[Python Kivy GUI Framework]] - more advanced, modern and also Cross-Platform with Mobile
- [[Python TKinter GUI Framework]] - basics, for beginners, but also powerful
- [[Python PySimpleGUI Framework]] - combining several GUI Frameworks and make them easier to use
## Install Python Modules with pip3
- Install Data Science Modules **Pandas** with `pip3 install pandas`
- **[fdb](https://fdb.readthedocs.io/en/latest/)** for [[Firebird DB]] handling and [[Firebird mit Python]]
- **[prettytable](https://pypi.org/project/prettytable/)** to print CSV pretty
- **[Pandas](https://pandas.pydata.org/)** for Data manipulation
- Dependecies
- **openpyxl** für `.xlsx`
- **xlwt** für `.xls`
## Print outputs
- **Use multiple variables:** `print("Line {}: {} / {}".format(rowCounter, i, len(foundKabelNormSorted)))`
## Strings
- **Find position of Substring:** `"This is the String!".find("is") => 5`
### Multiple lines
- e.g. for SQL Statements
```python
sqlStecker = """
SELECT
TRIM(a.ARTIKELNR) AS "Artikel-Nr.",
a.BEZEICHNUNG,
a.TEXT,
a.BEZEICHNUNG8,
a.FREIFELD15 AS "Steckernorm",
a.FREIFELD16 AS "Steckertyp",
a.FREIFELD17 AS "Kabel 1",
a.FREIFELD18 AS "Kabel 2",
a.FREIFELD19 AS "Kabel 3",
a.FREIFELD20 AS "Kabel 4",
a.FREIFELD21 AS "Kabel 5"
FROM ARTIKEL a
WHERE
TRIM(a.ARTIKELNR) NOT LIKE '10%'
AND TRIM(a.ARTIKELNR) NOT LIKE '2%'
AND upper(TRIM(a.BEZEICHNUNG)) NOT LIKE '%PIN%'
AND TRIM(a.BEZEICHNUNG) NOT LIKE '%Versand%'
AND TRIM(a.ARTIKELNR) NOT LIKE '%-%'
AND TRIM(a.ARTIKELNR) NOT LIKE '%.%'
ORDER BY a.ARTIKELNR ASC;
"""
```
## Date and Time
```python
import datetime
today = datetime.date.today()
```
## File Handling
### Open and read line by line
```python
fileOpened = open(fileName, 'r')
fileLines = fileOpened.readlines()
count = 0
for line in fileLines:
count += 1
print("Line {}: {}".format(count, line.strip()))
```
See handling *CSV files* in another chapter.
### Delete File
```python
import os
os.remove("demofile.txt")
```
## Handle and Output CSV Data and Files
- Open / write CSV files
- output nice with **PrettyTable**
- Handle data and output nice with Module **Pandas**
### Open CSV File
```python
fileOpened = open(fileName, 'r')
csv_f = csv.reader(fileOpened)
count = 0
for row in csv_f:
count += 1
print("Line {}: {}".format(count, row[4]))
```
### Write CSV Data to .csv file
```python
import csv
with open(filename, 'w') as csvFile:
csvWriter = csv.writer(csvFile)
csvWriter.writerow(tableHeaders)
for row in datalist:
csvWriter.writerow(row)
```
### Output CSV data from list ect. nice
```python
from prettytable import PrettyTable
outputTable = PrettyTable()
for row in dataList:
outputTable.add_row(row)
outputTable.align = "l"
print(outputTable)
```
### Open CSV File and Output nice
```python
from prettytable import from_csv
# Output CSV File as pretty readable table
with open(outputFilename) as csvFile:
mytable = from_csv(csvFile)
mytable.align = "l"
print(mytable)
```
## [[Firebird mit Python]]
## WebDAV Upload File
```python
file = open(filename,'rb')
url = nextcloudUrl+'/SharedFiles/' + filename
r = requests.put(url, file, auth = HTTPBasicAuth(nextcloudUser, nextcloudPw))
print(r.text)
```
## Handling Data with Module Pandas
- **[Pandas](https://pandas.pydata.org/)** for Data manipulation
- [Doku - pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html)
- [How to Add a Column to a DataFrame in Python Pandas](https://pythonguides.com/add-a-column-to-a-dataframe-in-python-pandas/)
- Dependecies
- **openpyxl** für `.xlsx`
- **xlwt** für `.xls`
```python
import pandas
dataFrame = pandas.DataFrame(data=dataList, columns=tableHeaders)
# set Datatypes for each column -> especially for Float values
# to have correctly displayed values in Excel: 1.45 -> 1,45
dataFrame = dataFrame.astype(dtypes)
# add Column at location=0 -> also vorne
dataFrame.insert(loc=0, column=datetime.datetime.today(), value='0', allow_duplicates=True)
# als .xls oder .xlsx
dataFrame.to_excel(outputFilename, sheet_name="sheetName.xlsx", float_format='%.2f', index= None, header=True)
# print Dataframe as nice table -> PrettyTable not needed
print(dataFrame)
```
## if String Contains a Substring
```python
strings = ['This string has apples', 'This string has oranges', 'This string has neither']
for s in strings:
if 'apples' in s:
print('Apples in string')
else:
print('Apples not in string')
```
## Placeholders in Strings
- using `%s`
## Lists etc
- **Sort List:** `sorted(dataList)`
- **List Length:** `len(thislist)`
### Lists []
- **Add new item** `listVar.append(item)`
- **Combine two lists:** `listVar.extend(itemList)`
- **Add new member on first Position:** `listVar.insert(0,itemValue)`
### Dictionary {}
```python
>>> students = {"Tobi":27, "Ewe":22, "Flo":25}
>>>
>>> students.keys()
>>>
>>> students.values()
```
### Tupel ()
- cannot be modified
- cannot delete Items of Tupel
- only delete whole Tupel
```python
>>> tup1 = (13,14,16,"Apfel")
```
## Conditional Statements
```python
>>> age = 5
>>> if (age > 3):
print("greter 3")
elif (age = 5):
print("equals 5")
else:
print("nothing")
equals 5
>>> 3 >= 2
True
>>> 3 <= 2
False
>>> 3 == 3
True
>>> 3 != 3
False
>>> 3 != 2
True
>>> 5 = 3
File "<input>", line 1
SyntaxError: can't assign to literal
```
## For Loops
- using `range()` function
- `range(1,10)`
- `range(1,10,2)` -> increment factor
- `range(0,51,5)`
```python
>>> list1 = ["Apfel", "Bananen", "Kirschen"]
>>> tup1 = (13,12,15)
>>> for item in list1:
print(item)
"""Apfel
Bananen
Kirschen
"""
for i in range(0,10):
print(i)
"""
0
1
2
3
4
5
6
7
8
9
"""
for i in range(0,10,2):
print(i)
"""
0
2
4
6
8
"""
```
## While Loops
- `break`
- `continue`
- `pass` = has no content, mark as "TODO", that some code will follow
```python
# break
>>> c = 0
>>> while c < 5:
print(c)
if c == 3:
break
c = c +1
"""
0
1
2
3
"""
# continue
>>> c = 0
>>> while c < 5:
c = c + 1
if c == 3:
continue
print(c)
"""
1
2
4
5
"""
```
## Try und Except
```python
>>> try:
if name > 3:
print("Hello")
except:
print("Fehler!!!")
"""
Fehler!!!
"""
```
## Functions
```python
# function definiton
def HelloWorld():
print("Hello World!")
# function call
HelloWorld()
def Greeting(name):
print("Hi " + name + "!")
Greeting("Tobi")
def plus(num1, num2):
print(num1 + num2)
plus(1,9)
# return
def returnPlus(num1, num2):
return(num1 + num2)
sum = returnPlus(22,33)
print(sum)
# Run will output:
"""
Hello World!
Hi Tobi!
10
55
"""
```
## Call Python script with parameters
- import sys out of hello function.
- arguments should be converted to int.
- String literal that contain ' should be escaped or should be surrouned by ".
- Did you invoke the program with `python hello.py some-number some-number` in command line?
```python
import sys
def hello(a,b):
print "hello and that's your sum:", a + b
if __name__ == "__main__":
a = int(sys.argv[1])
b = int(sys.argv[2])
hello(a, b)
```
## Add Section Numbers
```python
with open('00.00_Title.md','r') as f:
with open('test1.txt','w') as g:
for x in f:
#x = x.rstrip()
if not x: continue
print (x)
```
#
***
Related:
- [[$-Software|Software]]
- [[$-Automatisierung]]