一、文件操作步骤:
1. 打开文件 (open)(事先新建好txt)
file = open(r"D:\QC\python\test.txt", "r")
r:防止转义 "D:\QC\python\test.txt":文件路径 "r":只读形式
2. 读、写文件(read、write)
txt = file.read()
print(txt)
3. 关闭文件 (close)
file.close()
新建test.txt:
新建空文本test1.txt
二、追加写文件
file = open(r"D:\QC\python\test1.txt", "a") # a追加写
file.write("hi") # 新追加txt的内容
file.close()
修改文件内容
file = open(r"D:\QC\python\test.txt", "r") # 读的方式
txt = file.read() #先读出来
a = txt.replace("hello", "bye")
file.close() # 一定要关闭
file = open(r"D:\QC\python\test.txt", "w") # 写
file.write(a)
file.close()
结果:
三、复制文件
把文件test.txt的内容复制到test2.txt
思路:1)读取test中所有内容 2)打开test2文件用w写入,把内容写入
file = open(r"D:\QC\python\test.txt", "r")
txt = file.read()
file.close()
file = open(r"D:\QC\python\t