功能:去除 .c和.h文件中多余空格。此处的多余空格指的是行尾的空格和空行行首的空格。
环境:Windows 7旗舰版
Python:3.6.5
Version 1:(只支持单级目录)
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 2 09:23:17 2018
@author: sdc
"""
import sys
import os
import os.path
#判断参数是否正确
if len(sys.argv) < 2:
print('Wrong para, input file dir')
sys.exit()
#判断目录是否存在
#print(sys.argv[1])
if os.path.exists(sys.argv[1]):
currentPath = os.getcwd()
os.chdir(sys.argv[1]) #切换到目标目录
dirContents = os.listdir()#保存目录内容
# print(dirContents)
else:
print('Wrong dir')
sys.exit()
sourceFiles = []
for filename in dirContents:
if (filename[-2:] == '.c') | (filename[-2:] == '.h'):
sourceFiles.append(filename)
print('Source files:')
for filename in sourceFiles:
print(filename)
#使用with 方式,不用调用close()函数
with open(filename, 'r+', encoding='utf-8') as fileHandle:#不能以'a+'的方式打开
fileContents = fileHandle.readlines()
if len(fileContents) == 0:
print('%s file is empty' % filename)
continue
finalLineContent = fileContents[-1]
if finalLineContent[-1] != '\n':#确保最后一行有换行符
finalLineContent = finalLineContent + '\n'
fileContents[-1] = finalLineContent
#print(fileContents)
newFileContents = [] #存储修改后的内容,最终将其写入文件中
for lineContent in fileContents:
newLineContent = lineContent[:-1] #去除 \n
if newLineContent.strip() != '': #如果去除首尾的空格后不为空,那么只应该去掉行尾的空格
newLineContent = newLineContent.rstrip() + '\n'
else:
newLineContent = newLineContent.strip() + '\n'
newFileContents.append(newLineContent)
fileHandle.seek(0, 0) #将文件指针放在文件开头
fileHandle.truncate() #清空文件
#print(newFileContents)
fileHandle.writelines(newFileContents) #写入修改后的内容
os.chdir(currentPath)
使用方式:
python test.py dirname