我正在编写一个脚本,该脚本可以从放置在目录内的文本文件中删除空白行和前导空格。这有点有效。我遇到的问题是,当我第一次在记事本中打开文件然后保存它时,脚本仅创建预期的输出。无需对文件进行任何更改,只需打开和保存文件即可使其工作。如果我不打开并保存文件,我最终只会得到原始文件、空格和所有内容的副本。
我使用的是 python 3 和 windows 8。
import os
import glob
import re
def cleanLeadingWhiteSpace(inputSrc, outputDest):
for line in inputSrc:
cleanLine = (line.lstrip())
if re.match(r'^\s*$', cleanLine):
print ('blank line removed')
outputDest.write(cleanLine)
for file in glob.glob('input\*.txt'):
sourceFile = open (file,'r+')
outputFileName = ('output' + file[5:])
outputFile = open (outputFileName,'w+')
print ('Output File: ',outputFileName)
cleanLeadingWhiteSpace(sourceFile,outputFile)
感谢您的建议。
最佳答案
我建议重构您的函数以采用文件名而不是文件对象,但如果您坚持这样做,请改为这样做:
import os, glob
def clean_leading_whitespace(src, dst):
for line in src:
cleaned = line.lstrip()
if cleaned == "":
print ('blank line removed')
# matches an empty string, e.g. a blank line
dst.write(cleaned)
for file in glob.glob('input\*.txt'):
dst_name = 'output' + file[5:]
with open(file, 'r+') as src, open(dst_name, 'w+') as dst:
clean_leading_whitespace(src,dst)
# Context manager makes sure your files are closed
print("Output file: ", dst_name)
关于python - 在保存到记事本之前,不会使用 python 脚本对文件进行任何更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25732256/