#1、打开文件 如果文件不存在会报错 file = open("1.txt") #2、使用w、w+、a、a+模式打开,如果文件不存在就创建文件 file = open("1.txt", "w") #3、指定绝对路径路径 file = open("D:\\1.txt", "w") #二进制模式打开图片或者视频 file = open("老虎头像.png", "rb") print(file) #指定字符集打开文件 file = open("csv群聊.csv", "r", encoding='utf-8') #关闭文件 file.close() #写入文件 复写 file = open("1.txt","w") file.write("1111你好") #写入文件 追加 file = open("1.txt","a") file.write("123123") # 打开文件 读取前9字符串 file = open("messages.txt", "r", encoding='utf-8') string = file.read(9) print(string) #想要从文件的第6个字符开始读取2个字符 file = open("messages.txt", "r", encoding='utf-8') file.seek(5) # 移动指针到新的位置 string = file.read(2) # 读取2个字符 print(string) #读取一行 print("\n", "=" * 20, "Python经典应用", "=" * 20) with open1("messages.txt", "r", encoding="utf-8") as file: number = 0 # 记录行号 while True: number += 1 line = file.readline() if line == "": break print(number, line, end="\n") print("\n ", "=" * 20, "over" * 20, "\n") #读取一行并将内容分割 print("\n", "=" * 20, "Python经典应用", "=" * 20) with open2("csv群聊.csv", "r", encoding="utf-8") as file: number = 0 # 记录行号 while True: number += 1 line = file.readline() if line == "": break else: print(number, line, end="\n") lst = line.split(' ')#使用空字符串分割 for i in range(len(lst)): print(i, lst[i]) print("\n ", "=" * 20, "over" * 20, "\n") #读取全部行 一次性输出 print("\n", "=" * 20, "Python经典应用", "=" * 20) with open3("messages.txt", "r", encoding="utf-8") as file: message = file.readlines() # 读取全部信息 print(message) print("\n ", "=" * 20, "over", "=" * 20, "\n") # 读取全部行 将列表的内容逐行输出 print("\n", "=" * 20, "Python经典应用", "=" * 20) with open4("messages.txt", "r", encoding="utf-8") as file: messageall = file.readlines() # 读取全部信息 for message in messageall: print(message) # 输出一条信息 print("\n ", "=" * 20, "over", "=" * 20, "\n")
标签:文件,20,读取,python,处理,file,print,txt,open From: https://www.cnblogs.com/yclh/p/17127883.html