【编程】python文件读写

我把python文件读写函数进一步封装成了傻瓜式函数,开箱即用,傻瓜操作,极其实用。

包括:复制文件读文件写文件,后面还有一个删除文件

 1 # coding:utf-8
 2 import shutil
 3 #把source_file拷贝到target_file里。
 4 #注意,可以把aa.md拷贝成bb.txt,格式会自动转换
 5 #若被写入文件不存在,则会自动创建;若存在,则会将其覆盖掉
 6 def copy_file(source_file,target_file):
 7     shutil.copyfile(source_file, target_file)
 8 
 9 #清空文件file里的所有内容
10 def qingkong_file(file):
11     file_obj2 = open(file, 'w')
12     file_obj2.seek(0)  # 把文件定位到position 0
13     file_obj2.truncate()  # 清空文件
14     file_obj2.close()
15 
16 #把字符串the_str写入文件
17 #arg是写入模式的参数,'a'为追加写入,'w'为覆盖写入
18 #若被写入文件不存在,则会自动创建
19 def write_file(file,the_str,arg):
20     #关键字with在不需要再访问文件后系统自动将其关闭
21     with open(file,arg, encoding='UTF-8') as file_obj2:  # a为追加写入,w为覆盖写入
22         file_obj2.write(the_str)
23 
24 #读取并以字符串形式返回文件所有内容
25 def read_file(file):
26     with open(file,'r', encoding='UTF-8') as file_obj:
27         contents = file_obj.read()
28         return contents
29 
30 #逐行读取文件并打印
31 def read_file_by_line(file):
32     with open(file,'r', encoding='UTF-8') as file_obj:
33         for line in file_obj:
34             print(line)

 删除文件:

1 import os
2 os.remove("demofile.txt")

 

posted @ 2021-05-23 20:21  林间飞鹿  阅读(74)  评论(0编辑  收藏  举报