2022.11.16 本学习内容总结于莫烦python:4.文件管理
https://mofanpy.com/tutorials/python-basic/interactive-python/read-write-file
均是用特殊字符open
f = open("new_file.txt", "w") # 创建并打开
f.write("some text...") # 在文件里写东西
f.close() # 关闭
w
是写权限,会有相应的读等等(后面讲)…
|- me.py
|- new_file.txt
with open("new_file2.txt", "w") as f:f.writelines(["some text for file2...\n", "2nd line\n"])
w
改成 r
。 也就是说,其实 w
代表的是 write
, r
代表的是 read
f = open("new_file2.txt", "r")
print(f.read())
f.close()
some text for file2...
2nd line
writelines()
,那么在读文件的时候, 也可以 readlines()
直接读出来一个列表with open("new_file2.txt", "r") as f:print(f.readlines())
['some text for file2...\n', '2nd line\n']
输出是个列表【】
with open("new_file2.txt", "r") as f:while True:line = f.readline()print(line)if not line:break
【知识点】
open()
函数打开的文件,在操作完成之后,一定要调用 close()
函数将其关闭吗?答案是肯定的。文件在打开并操作完成之后,就应该及时关闭,否则程序的运行可能出现问题。with open()
,不需要写close
语句,默认自动帮我们关闭文件参考:
http://c.biancheng.net/view/4770.html
https://www.cnblogs.com/annatest/p/13092135.html
原文件的编码,通常来说是 utf-8、gbk、gb2312其中的某一种。
文件在 Windows 存储的时候,是以 gbk 的格式存储的
with open("chinese.txt", "wb") as f:f.write("这是中文的,this is Chinese".encode("gbk"))
wb
,意思是 write binary
(二进制写)形式,取代默认的 text
形式
读的时候 要制定编码,不然打不开或乱码
with open("chinese.txt", "rb", ) as f:#print(f.read()) # 乱码print(f.read().decode('gbk')) # windows在本机尝试,可以试试这个
# 下面的代码会报错
with open("chinese.txt", "r") as f:print(f.read())
#可以
with open("chinese.txt", "r", encoding="gbk") as f:print(f.read())
这是中文的,this is Chinese
with open("new_file.txt", "r") as f:print(f.read())
with open("new_file.txt", "r+") as f:f.write("text has been replaced")f.seek(0) # 将开始读的位置从写入的最后位置调到开头print(f.read())
some text...
text has been replaced
.seek(0)
,不然光标在文档末尾,第六行的print(f.read())
没有输出print(f.read())
:print(f.read())
,但其实内容输出后已经更改os库是Python自带的一个非常有用的模块。如果你做一个系统性的东西,要处理文件输出,读入等问题, 那么你有80%概率会使用到os库中的一些功能。
os.getcwd()、 os.listdir()
import os print("当前目录:", os.getcwd())
print("当前目录里有什么:", os.listdir())
当前目录: /home/pyodide
当前目录里有什么: ['files']
os.makedirs
os.makedirs("project", exist_ok=True)
print(os.path.exists("project"))# 这句话是用来检测是否存在的,创建只是上面那句
shutil.rmtree()
用户注册了我这个系统,我得为这个用户创建一个他的文件夹。如果用户注销了,我是不是得把它的文件夹删掉?文件夹里有文件,不为空,就会报错的: 因为文件写了Nothing
os.makedirs("user/mofan", exist_ok=True)
with open("user/mofan/a.txt", "w") as f:f.write("nothing")
os.removedirs("user/mofan") # 这里会报错
这种事情,需要用到另一个库,名字叫做 shutil.rmtree()
,它可以清空整个目录(递归地删除文件)
import shutilshutil.rmtree("user/mofan")
print(os.listdir("user"))
[]
shutil.rmtree()
#递归地删除文件
os.rename()
os.makedirs("user/mofan", exist_ok=True)
os.rename("user/mofan", "user/mofanpy")
print(os.listdir("user"))
['mofanpy']
import os
os.makedirs("user/mofan", exist_ok=True)
with open("user/mofan/a.txt", "w") as f:f.write("nothing")
print(os.path.isfile("user/mofan/a.txt")) # True
print(os.path.exists("user/mofan/a.txt")) # True
print(os.path.isdir("user/mofan/a.txt")) # False
print(os.path.isdir("user/mofan")) # True
① 先拿到文件名 os.path.basename
② 再拿文件夹名 os.path.dirname
③ 为副本重命名
④ 把目录重新组合 os.path.join
import os
import shutildef copy(path):filename = os.path.basename(path) # 文件名dir_name = os.path.dirname(path) # 文件夹名new_filename = "new_" + filename # 新文件名new_path = os.path.join(dir_name, new_filename) # 目录重组shutil.copy2(path, new_path) # 复制文件return os.path.isfile(new_path), new_pathcopied, new_path = copy("user/mofan/a.txt")
if copied:print("copied to:", new_path)
else:print("copy failed")
os.path.join()
:目录拼接:https://blog.csdn.net/swan777/article/details/89040802
>>> import os
>>> print(os.path.join('path','abc','yyy'))
path\abc\yyy
shutil.copy2()
: Python中的方法用于将源文件的内容复制到目标文件或目录。此方法与shutil.copy()方法,但它还会尝试保留文件的元数据。
def copy(path):dir_name, filename = os.path.split(path)new_filename = "new2_" + filename # 新文件名new_path = os.path.join(dir_name, new_filename) # 目录重组shutil.copy2(path, new_path) # 复制文件return os.path.isfile(new_path), new_path
copied, new_path = copy("user/mofan/a.txt")
if copied:print("copied to:", new_path)
else:print("copy failed")
上一篇:【数据结构】模拟实现双向链表
下一篇:GoF之代理模式