import os #目录操做 def writeFile(): fo = open("foo.txt", "a+") #打开一个文件,第二个参数为打开的模式:r 只读,r+读写 w只写 w+读写 wb二进制方式只写 a 追加 print ("文件名: ", fo.name) print("是否已关闭 : ", fo.closed) print("访问模式 : ", fo.mode) fo.write("www.runoob.com!\nVery good site!") fo.close() #刷新缓冲区里任何还没写入的信息,并关闭该文件,这以后便不能再进行写入 print("是否已关闭 : ", fo.closed) def readFile(): fo = open("foo.txt", "r+") # 打开一个文件,第二个参数为打开的模式:r 只读,r+读写 w只写 w+读写 wb二进制方式只写 a 追加 print("文件名: ", fo.name) print("是否已关闭 : ", fo.closed) print("访问模式 : ", fo.mode) str = fo.read(10); print("读取的字符串是 : ", str) position = fo.tell(); print("指针当前文件位置 : ", position) # 把指针再次从新定位到文件开头 position = fo.seek(0,0); str = fo.read(10); print("从新读取字符串 : ", str) fo.close() # 刷新缓冲区里任何还没写入的信息,并关闭该文件,这以后便不能再进行写入 print("是否已关闭 : ", fo.closed) #重命名 def dirFile(): fo = open("foo.txt", "w+")# fo.close() # 刷新缓冲区里任何还没写入的信息,并关闭该文件,这以后便不能再进行写入 print("建立文件名: ", fo.name) os.rename("foo.txt","oof.txt") print("修改文件名: ", fo.name) os.remove("oof.txt") # 建立目录test #os.mkdir("test") # 删除”/tmp/test”目录 #os.rmdir("/tmp/test") # 给出当前的目录 print(os.getcwd())
https://www.runoob.com/python/python-multithreading.htmlhtml
import time, threading def threadtest(): thread1 = threading.Thread(target=printtime,args=("t1",2)); thread2 = threading.Thread(target=printtime, args=("t2", 4)); thread1.start() thread2.start() def printtime(threadname,delay): count=0 while count<5: time.sleep(delay) count += 1 print(threadname+":",time.strftime("%a %b %d %H:%M:%S %Y",time.localtime()))
若是多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,须要对多个线程进行同步。python
使用Thread对象的Lock和Rlock能够实现简单的线程同步,这两个对象都有acquire方法和release方法,对于那些须要每次只容许一个线程操做的数据,能够将其操做放到acquire和release方法之间。app
import time, threading class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("Starting " + self.name) # 得到锁,成功得到锁定后返回True # 可选的timeout参数不填时将一直阻塞直到得到锁定 # 不然超时后将返回False threadLock.acquire() print_time(self.name, self.counter, 3) # 释放锁 threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 threadLock = threading.Lock() threads = [] # 建立新线程 thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # 开启新线程 thread1.start() thread2.start() # 添加线程到线程列表 threads.append(thread1) threads.append(thread2) # 等待全部线程完成 for t in threads: t.join() # 等待至线程停止。这阻塞调用线程直至线程的join() 方法被调用停止-正常退出或者抛出未处理的异常-或者是可选的超时发生 print("Exiting Main Thread")