Python 件操作简单工具方法

python3 文件操作

需要导入os

1
import os

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 覆盖写入文件
def overwrite_to(s_file_path, s_content):
if os.path.exists(s_file_path):
os.remove(s_file_path)
produ_f = open(s_file_path, "a")
produ_f.write(f"{s_content}\n")
produ_f.close()

# 删除文件
def remove_file(s_file_path):
if os.path.exists(s_file_path):
os.remove(s_file_path)
else:
print(f"{s_file_path} file not exist")

# 追加内容
def append_to(s_file_path, s_content):
if os.path.exists(s_file_path):
produ_f = open(s_file_path, "a+")
produ_f.write(s_content)
produ_f.close()
else:
raise IOError(f"{s_file_path} file not exist")

喜欢请点个赞,

转载请注明出处:https://www.jianshu.com/u/4915ed24d1e3

如有错误,请务必指正!谢谢!

我的博客:https://xzing.github.io/