python - 在保存到记事本之前,不会使用 python 脚本对文件进行任何更改

标签 python python-3.x

我正在编写一个脚本,该脚本可以从放置在目录内的文本文件中删除空白行和前导空格。这有点有效。我遇到的问题是,当我第一次在记事本中打开文件然后保存它时,脚本仅创建预期的输出。无需对文件进行任何更改,只需打开和保存文件即可使其工作。如果我不打开并保存文件,我最终只会得到原始文件、空格和所有内容的副本。

我使用的是 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/

相关文章:

python-3.x - 如何在 Mac OS X Big Sur 上安装 Python 3.9 的 pandas 模块?

python - 如何纠正python错误: "icon object is not callable"?

postgresql - 如何加入 like % class.column %

python-3.x - 从一些外部 tf-idf 矩阵和术语列表中使用 gensim 训练 LDA 模型

python - 我在哪里可以找到 PyBluez API

python - 为什么 ZMQ 不会丢弃消息?

python - 对 `copy` 的 `numpy.astype` 属性感到困惑

python - 迭代文件以查找字符串并输出信息

c++ - 有没有办法在 Python 中执行 "template base class"?

python - 通过邮件发送创建的绘图