python简单文件操作

写软件著作申请,需要将所有源代码代码贴入一个word中,在源代码前后要添加一些标记,如下:

////////////////////////////
//filename1
////////////////////////////
your code1
////////////////////////////

////////////////////////////
//filename2
////////////////////////////
your code2
////////////////////////////

...

其中 filename 是源代码文件名,your code 是文件里的内容。

Python 代码(注释可能导致错误):

 1 import os
 2 
 3 def read_wrte_file(o, filename):
 4   f = open(filename) #打开文件
 5   o.write("//////////////////////////////////////////
") #没有writeline函数,write + 
 代替
 6   o.write("//"+os.path.basename(filename)) #从绝对路径中获得文件名,并写入out
 7   o.write("
//////////////////////////////////////////
")
 8   o.write(f.read()) #读取文件中所有内容,并写入out
 9   o.write("
//////////////////////////////////////////

")
10   f.close()
11   
12 def process_file(o, filename):
13   if os.path.isfile(filename): #如果file是文件,直接将内容写到out中
14     read_wrte_file(o, filename)
15   elif os.path.isdir(filename): #如果是file文件夹
16     for name in os.listdir(filename): #获得文件夹里的file
17       name = filename + "/" + name #设置file的路径
18       process_file(o, name) #递归调用  深度优先
19   
20 out = open("out.txt", "w") #打开一个文件,用来输出
21 process_file(out, "D:workSpacecode") #用输出文件和放代码文件夹调用 文件or目录 处理函数
22 out.close()

用到的几个函数是分布在不同地方的:

1、open,close 是内嵌函数

2、write,read,listdir是 os 中的函数

3、isdir, isfile, basename 是 os.path 中的函数

一点想法:

为什么 listdir 是操作文件夹的,却和 write,read 放在 os 中? 因为文件夹也是一种文件,所以 文件->{普通文件文件夹}。

可以将文件夹看做内容是一行行其他文件普通文件文件夹)的普通文件

普通文件的读用各种 read,文件夹的读就比价单一,所以就用一个 listdir。

原文地址:https://www.cnblogs.com/kohlrabi/p/6100977.html