实验代码:
#-------统计指定文件夹以及子文件夹中所有txt文件的总数量-------
import os.path
dir = r'D:\pythontext'
m = 0
for parentdir, dirname, filenames in os.walk(dir):
for filename in filenames:
print(filename)
if os.path.splitext(filename)[1] == '.txt':
m = m + 1
print("该文件夹以及子文件夹中所有txt文件的总数量是:%d个"%m)
#----读取指定文件,并输出内容------
with open("D:\pythontext\实验1.txt",encoding='utf8')as fp:
print(fp.read())
fp.close()
#-------在读出内容的每行前面加上行号----------
with open("D:\pythontext\实验1.txt",'r',encoding='utf8')as fp:
lines=fp.readlines() #读取所有行
maxLength=len(max(lines,key=len))
lines=['#'+str(index+1)+line.rstrip().ljust(maxLength)+'\n'
for index,line in enumerate(lines)]
with open("D:\pythontext\实验1.txt"[:-4]+'_n