01-07. 装饰器&偏函数与作用域与异常处理与文件读写06

1 读文件

读文件过程如下:

  • 打开文件;
  • 读文件内容;
  • 关闭文件。

1.1 打开文件

open(path, flag[, encoding][, errors])

  • path:要打开文件的路径
  • flag:打开方式

    • r:以只读的方式打开文件,文件的描述符放在文件的开头;
    • rb:以二进制格式打开一个文件用于只读,文件的描述符放在文件的开头;
    • r+:打开一个文件用于读写,文件的描述符放在文件的开头;
    • w:打开一个文件只用于写入,如果该文件已经存在会覆盖,如果不存在则创建新文件;
    • wb:打开一个文件只用于写入二进制,如果该文件已经存在会覆盖,如果不存在则创建新文件;
    • w+:打开一个文件用于读写;
    • a:打开一个文件用于追加,如果文件存在,文件描述符将会放到文件末尾;
    • a+:
  • encoding:编码方式;
  • errors:错误处理。
  1. path = r"D:\PythonProj\test.txt"
  2. #ignore 忽略错误
  3. #f = open(path, "r", encoding="utf-8", errors="ignore")
  4. f = open(path, "r", encoding="utf-8")

1.2 读文件

读取文件全部内容

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str1 = f.read()
  4. print(str1)

读取指定字符数

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str2 = f.read(10)
  4. print("*"+str2+"*")

读取整行,包括”\n”字符

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str4 = f.readline()
  4. print(str4)
  5. str5 = f.readline()
  6. print(str5)

读取指定字符数

读取一行中固定字符数,很少用

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str6 = f.readline(10)
  4. print(str6)

读取所有行并返回一个列表

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. list7 = f.readlines()
  4. print(list7)

若给定的数字大于0,返回实际size字节的行数

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. list8 = f.readlines(25)
  4. print(list8)

修改描述符的位置(seek方法)

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str1 = f.read()
  4. print(str1)
  5. print("********")
  6. f.seek(10)
  7. str9 = f.read()
  8. print(str9)

1.3 关闭文件

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "r", encoding="utf-8")
  3. str1 = f.read()
  4. print(str1)
  5. f.close()

1.4 一个完整的过程

  1. path = r"D:\PythonProj\test.txt"
  2. try:
  3. f1 = open(path, "r", encoding="utf-8")
  4. print(f1.read())
  5. finally:
  6. if f1: #判断是否打开,如果打开失败,就不用关闭了
  7. f1.close()
  8. #简单方法,不用写close
  9. with open(path, "r", encoding="utf-8") as f2:
  10. print(f2.read())

2 写文件

01-08. 装饰器&偏函数与作用域与异常处理与文件读写01

正常写文件是将信息先写入缓冲区,然后刷新缓冲区时再写入文件。flush、close、缓冲区写满和遇到“\n”均会刷新缓冲区。

  1. path = r"D:\PythonProj\test.txt"
  2. f = open(path, "w")
  3. #1、将信息写入缓冲区
  4. f.write("sunck in")
  5. #2、刷新缓冲区
  6. #直接把内部缓冲区的数据立刻写入文件,而不是被动的等待自动刷新缓冲区写入
  7. f.flush()
  8. f.close()

使用with可以简写,不用写flush和close。

  1. path = r"C:\Users\xlg\Desktop\Python-1704\day08\1-文件读写\file2.txt"
  2. with open(path, "a") as f2:
  3. f2.write("good man")

编码

01-08. 装饰器&偏函数与作用域与异常处理与文件读写02

  1. path = r"D:\PythonProj\test.txt"
  2. with open(path, "wb") as f1:
  3. str = "test凯"
  4. f1.write(str.encode("utf-8")) #不编码就会报错
  5. with open(path, "rb") as f2:
  6. data = f2.read()
  7. print(data) #b'test\xe5\x87\xaf'
  8. print(type(data)) #<class 'bytes'>
  9. newData = data.decode("utf-8")
  10. print(newData) #test凯
  11. print(type(newData)) #<class 'str'>

3 特殊文件读写

list-tuple-dict-set的文件操作

01-08. 装饰器&偏函数与作用域与异常处理与文件读写03

  1. import pickle #数据持久性模块
  2. myList = (1,2,3,4,5,"sunck is a good man")
  3. path = r"D:\PythonProj\test.txt"
  4. f = open(path, "wb")
  5. pickle.dump(myList, f)
  6. f.close()
  7. #读取
  8. f1 = open(path, "rb")
  9. tempList= pickle.load(f1)
  10. print(tempList)
  11. f1.close()

4 os模块

01-08. 装饰器&偏函数与作用域与异常处理与文件读写03

  1. import os
  2. #获取操作系统类型 nt->windows posix->Linux、Unix或Mac OS X
  3. print(os.name)
  4. #打印操作系统详细的信息(windows不支持)
  5. #print(os.uname())
  6. '''
  7. posix.uname_result(sysname='Darwin', nodename='sunck.local', release='15.5.0', version='Darwin Kernel Version 15.5.0: Tue Apr 19 18:36:36 PDT 2016; root:xnu-3248.50.21~8/RELEASE_X86_64', machine='x86_64')
  8. '''
  9. #获取操作系统中的所有环境变量
  10. #print(os.environ)
  11. #获取指定环境变量
  12. #print(os.environ.get("APPDATA"))
  13. #获取当前目录 ./a/
  14. print(os.curdir)
  15. #获取当前工作目录,即当前python脚本所在的目录
  16. print(os.getcwd())
  17. #以列表的形式返回指定目录下的所有的文件
  18. print(os.listdir(r"C:\Users\xlg\Desktop\Python-1704\day08"))
  19. #在当前目录下创建新目录
  20. #os.mkdir(r"C:\Users\xlg\Desktop\Python-1704\day08\kaige")
  21. #os.mkdir("sunck")
  22. #删除目录
  23. #os.rmdir("sunck")
  24. #获取文件属性
  25. #print(os.stat("sunck"))
  26. #重命名
  27. #os.rename("sunck", "kaige")
  28. #删除普通文件
  29. #os.remove("file1.txt")
  30. #运行shell命令
  31. #os.system("notepad")
  32. #os.system("write")
  33. #os.system("mspaint")
  34. #os.system("msconfig")
  35. #os.system("shutdown -s -t 500")
  36. #os.system("shutdown -a")
  37. #os.system("taskkill /f /im notepad.exe")
  38. #有些方法存在os模块里,还有些存在于os.path
  39. #查看当前的绝对路径
  40. print(os.path.abspath("./kaige"))
  41. #拼接路径
  42. p1 = "C:\\Users\\xlg\\Desktop\\Python-1704\\day08\\"
  43. p2 = r"sunck\abc\d"
  44. #注意:参数2里开始不要有斜杠
  45. #r"C:\Users\xlg\Desktop\Python-1704\day08\sunck"
  46. p3 = "/root/sunck/home"
  47. p4 = "kaige"
  48. #/root/sunck/home/kaige
  49. print(os.path.join(p3, p4))
  50. #拆分路径
  51. path2 = r"C:\Users\xlg\Desktop\Python-1704\day08\2-os模块\kaige.txt"
  52. print(os.path.split(path2))
  53. #获取扩展名
  54. print(os.path.splitext(path2))
  55. #判断是否是目录
  56. print(os.path.isdir(path2))
  57. #判断文件是否存在
  58. path3 = r"C:\Users\xlg\Desktop\Python-1704\day08\函数也是一种数据类型.py"
  59. print(os.path.isfile(path3))
  60. #判断目录是否存在
  61. path4 = r"C:\Users\xlg\Desktop\Python-1704\day081"
  62. print(os.path.exists(path4))
  63. #获得文件大小(字节)
  64. print(os.path.getsize(path3))
  65. #文件的目录
  66. print(os.path.dirname(path3))
  67. print(os.path.basename(path3))

5 窗口控制

01-08. 装饰器&偏函数与作用域与异常处理与文件读写05

  1. import win32con
  2. import win32gui
  3. import time
  4. #找出窗体的编号
  5. #QQWin = win32gui.FindWindow("TXGuiFoundation", "QQ")
  6. #隐藏窗体
  7. #win32gui.ShowWindow(QQWin, win32con.SW_HIDE)
  8. #显示窗体
  9. #win32gui.ShowWindow(QQWin, win32con.SW_SHOW)
  10. while True:
  11. QQWin = win32gui.FindWindow("Chrome_WidgetWin_1", "新标签页 - Google Chrome")
  12. win32gui.ShowWindow(QQWin, win32con.SW_HIDE)
  13. time.sleep(1)
  14. win32gui.ShowWindow(QQWin, win32con.SW_SHOW)
  15. time.sleep(1)

01-08. 装饰器&偏函数与作用域与异常处理与文件读写06

  1. import win32con
  2. import win32gui
  3. import time
  4. import random
  5. QQWin = win32gui.FindWindow("TXGuiFoundation", "QQ")
  6. #参数1:控制的窗体
  7. #参数2:大致方位,HWND_TOPMOST上方
  8. #参数3:位置x
  9. #参数4:位置y
  10. #参数5:长度
  11. #参数6:宽度
  12. while True:
  13. x = random.randrange(900)
  14. y = random.randrange(600)
  15. win32gui.SetWindowPos(QQWin,win32con.HWND_TOPMOST,x, y, 300, 300, win32con.SWP_SHOWWINDOW)

6 内存修改

01-08. 装饰器&偏函数与作用域与异常处理与文件读写07

7 作业

01-10. 模块的使用与面向对象思想简介04

  1. import os
  2. import collections
  3. def work(path):
  4. resPath = r"C:\Users\xlg\Desktop\Python-1704\day10\res"
  5. #打开文件
  6. with open(path, "r") as f:
  7. while True:
  8. #laphael1985@163.com----198587
  9. lineInfo = f.readline()
  10. if len(lineInfo) < 5:
  11. break
  12. #邮箱的字符串
  13. #laphael1985 @ 163.com
  14. mailStr = lineInfo.split("----")[0]
  15. #邮箱类型的目录
  16. #C:\Users\xlg\Desktop\Python-1704\day10\res\163
  17. #print(mailStr)
  18. fileType = mailStr.split("@")[1].split(".")[0]
  19. dirStr = os.path.join(resPath,fileType)
  20. if not os.path.exists(dirStr):
  21. #不存在,创建
  22. os.mkdir(dirStr)
  23. filePath = os.path.join(dirStr, fileType + ".txt")
  24. with open(filePath, "a") as fw:
  25. fw.write(mailStr+"\n")
  26. def getAllDirQU(path):
  27. queue = collections.deque()
  28. queue.append(path)
  29. while len(queue) != 0:
  30. dirPath = queue.popleft()
  31. filesList = os.listdir(dirPath)
  32. for fileName in filesList:
  33. fileAbsPath = os.path.join(dirPath, fileName)
  34. if os.path.isdir(fileAbsPath):
  35. queue.append(fileAbsPath)
  36. else:
  37. #处理普通文件
  38. work(fileAbsPath)
  39. getAllDirQU(r"C:\Users\xlg\Desktop\Python-1704\day10\newdir2")