This is first class for learning python, including

Toy examples

1/2019
0.0004952947003467063
type(1/2019)
float
f1=open(r'C:\py2020\test1.py','w')
f1=open('C:\\py2020\\test2.py','w')

Import the third part module, such as math

#help(zip)
#help(float)
import math
math.floor(5.4)
math.pi
3.141592653589793

Define your owen functions

def add(x,y):
    z = x+y
    return(z)

add(3,4)
7

Default arguments in your owen function

def add(x,y=1):
    z = x+y
    return(z)

add(3)
4

Default arguments must not be before non-default arguments.

def add(x=0,y):
    z = x+y
    return(z)

add(3)
7

Treat fuctions as arguments of another function.

def add(x,y=1):
    z = x+y
    return(z)

def self(add,x):
    return add(x,2)

self(add,3)
5

Lambda function

add1 = lambda x,y: x+y
add1(3,4)
7

Open files, read data

Close, read, and write

# help(open)
f = open(r'C:\py2020\data1.txt','w')
f.write("Hello world!")
f.close()
with open(r'C:\py2020\data1.txt','w') as f:
    f.write("Hello world!")
with open(r'C:\py2020\data1.txt') as f:
    p1 = f.read(5)
    p2 = f.read()
    print(p1,p2)
Hello  world!
with open(r'C:\py2020\data2.txt') as f:
    # p1 = f.readline()
    p2 = f.readlines()
    # print(p1)
    print(p2)
['Hello world!\n', '12,2\n', '3.1415926']

Syntax of f.seek()

with open(r'C:\py2020\data2.txt') as f:
    p1 = f.readlines()

for i in range(0,len(p1)):
    p1[i] = p1[1] 
    print(p1)
['12,2\n', '12,2\n', '3.1415926']
['12,2\n', '12,2\n', '3.1415926']
['12,2\n', '12,2\n', '12,2\n']
with open(r'C:\py2020\data3.txt','a+') as f:
    f.writelines("Hello world!\n")
    f.seek(0)
    p1 = f.readlines()
    print(p1)
['Hello world!\n']

Count lines from several different files.

def nlinesFiles(filename):
    try:
        with open(filename) as f:
            data = f.readlines()
    except FileNotFoundError:
        print(filename+'does not exist!')
    lens = len(data)
    print(filename+' has '+ str(lens) +' lens.')
    
files = ['data1.txt','data2.txt','data3.txt']
for fname in files:
    nlinesFiles(fname)            
data1.txt has 1 lens.
data2.txt has 3 lens.
data3.txt has 1 lens.
import os, shutil
def nlinesFiles(filename):
    try:
        with open(filename) as f:
            data = f.readlines()
    except FileNotFoundError:
        print(filename+'does not exist!')
    lens = len(data)
    print(filename+' has '+ str(lens) +' lens.')
   
path = './testdata'
files = ['data1.txt','data2.txt','data3.txt']
for fname in os.listdir(path):
    if fname.endswith('.txt'):
        filepath = os.path.join(path,fname)
        nlinesFiles(filepath) 
        
        if os.path.exists('./output'):
            shutil.rmtree('./output')
        os.mkdir('./output')
./testdata\data1.txt has 1 lens.
./testdata\data2.txt has 3 lens.
./testdata\data3.txt has 1 lens.