10th step for python:file operate (open ,read, write, close) && file operter && windows control && c

  1. open ,operte,close


fp = open ( "a.txt" , "r+" )
fw = open ( "b.txt" , "w" )
a = fp.read()
print (a)
s = "aaaaaa"
fw.write(a) #this opertor will be excuted when the file closed,is not imediately to do.
fw.flush() #if we want to inmediately to write it to file in stead of in the end_time to write,
fp.close()
fw.close()
print ( "你好" )
#readline()

a.seek(0)#set the index to start position

another way to open file,it will be automatic to closed the strem for open fil e:

with open(path, "r", encoding="utf-8") as f :
    print("11111"+ f.read())
  1. file and dirctory operte

os.rename('./1.txt','./nih/1.txt')
print(os.stat('./1.txt'))#show the information of the file
os.system('notepad')
print(os.path.abspath('.'))
# str1 = ''
# str2 =''
# os.path.join(str1,str2)

# path2=''
# print(os.path.split(path2))

path = "./1.txt"
os.path.isfile(path)#the file exist
path2 = "./nihao/"
os.path.exists(path2)#the dirctory exist

os.path.getsize(path)
os.path.dirname(path)
os.path.basename(path)#get file's name
  1. code format
# coding=gbk
# conding=utf8
# *-* conding=gbk *-*
#-!- coding: gbk -!-
  1. windows control
import win32con
import win32gui
import time
QQWin = win32gui.FindWindow("TXGuiFoundation", "TIM")
while True:
    win32gui.ShowWindow(QQWin, win32con.SW_SHOW)
    time.sleep(2)
    win32gui.ShowWindow(QQWin, win32con.SW_HIDE)
    time.sleep(2)

# -!- coding: gbk -!-
import win32con
import win32gui
import time,random
import win32com.client
# while True:
#     QQWin = win32gui.FindWindow("TXGuiFoundation", "TIM")
#     win32gui.ShowWindow(QQWin, win32con.SW_SHOW)
#     time.sleep(2)
#     win32gui.ShowWindow(QQWin, win32con.SW_HIDE)
#     time.sleep(2)
# while True:
#     time.sleep(2)
#     x =random.randint(0,900)
#     y = random.randint(0,800)
#     QQWin = win32gui.FindWindow("TXGuiFoundation", "TIM")
#     win32gui.SetWindowPos(QQWin,win32con.HWND_TOPMOST,x,y,20,10,win32con.SWP_SHOWWINDOW )

speak = win32com.client.Dispatch("SAPI.SPVOICE")
speak.Speak("nihao , woshisahua你好")
  1. encode and decode
python 3.6 does have the decode function
#-!- coding: gbk -!-
with open(path2,"wb") as f1 :
    str = "sdfd你好"
    f1.write(str.encode('gbk'))
with open(path2, "r") as f2 :
    a = f2.read()
    print("%s"%a)
  1. instant data
import pickle
mylist=(1,2,3,4,5)
path = ...
f = open(path,"wb")
pickle.dimp(mylist,f)
f.close()

f2 = open(path,"rb")
m.list = pickle.load(f2)
f2.close()
  1. eval
eval(str)
it makes "str" a excute sentence
like :
srt = "print(\"nihao\")"
eval(srt)
the same to 
print("nihao")
str = 1
while str != " " :
    try:
        str = input("输入命令")
        print(eval(str))
    except SyntaxError:
        pass
if we input :
__import__('os').system("dir")
will show the directory like use "dir" in system console does.

猜你喜欢

转载自blog.csdn.net/qq_14942375/article/details/80729187