f = open(r'F:\文档\珍爱网模版.txt', 'r') print(f.read()) f.seek(0) # .seek将光标移动到0位操作 f.close() # .close关闭文件操作,不操作也可以,python有垃圾回收机制
f = open(r'F:\文档\珍爱网模版.txt', 'r') print(f.read()) f.seek(0) # .seek将光标移动到0位操作 print(f.read(4)) f.seek(0) l = f.readlines() # 读取所有的行到一个列表 print(l) f.seek(0) print(f.readline()) # 读取下一行 f.seek(0) for line in l: print(line) for line in f: print(line, end='') f.close() # .close关闭文件操作,不操作也可以,python有垃圾回收机制 f = open(r"f:\文档\珍爱网.txt", encoding='utf8') print(f.read()) f.seek(0) import os # 操作系统功能模块 print(os.getcwd()) # 查看当前文件路径 os.chdir(r'f:\文档') print(os.getcwd()) f = open(r'珍爱网.txt', encoding='utf8') print(f.read())
import os os.getcwd() os.chdir(r'f:\文档') print(os.getcwd()) coures = open('coures.txt', 'w', encoding='utf8') coures.write("机构:腾讯课堂\n") coures.close() # 加上.close操作才可以在文件里保存写入的内容 names = ['Tom', 'Jerry', 'Mike', 'Jack'] f = open('people.txt', 'w', encoding='utf8') f.writelines(names) f.flush() # 将内存里缓存的内容直接映射在目标文件里 names = [name + '\n' for name in names] print(names) f = open('people.txt', 'w', encoding='utf8') # 'w'写操作会覆盖原有内容 f.writelines(names) print(f.flush()) l = ['John\n', 'Mary\n'] f = open('people.txt', 'a', encoding='utf8') f.writelines(l) print(f.flush()) f.close() # 日常写代码容易忘掉 with open('people.txt', 'r', encoding='utf8') as f: # 用 with, as 围绕f变量设置个上下文以:缩进 for line in f: print(line) with open('test.txt', 'w', encoding='utf8') as f: f.write('Hello\n') f.write('world\n') print(f)