Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在保存到记事本之前,不使用python脚本更改文件_Python_Python 3.x - Fatal编程技术网

在保存到记事本之前,不使用python脚本更改文件

在保存到记事本之前,不使用python脚本更改文件,python,python-3.x,Python,Python 3.x,我正在编写一个脚本,它可以从目录中的文本文件中删除空行和前导空格。这有点管用。我遇到的问题是,当我第一次在记事本中打开文件并保存它时,脚本只会创建预期的输出。无需对文件进行任何更改,只需打开并保存文件即可。如果我不打开并保存该文件,我最终只会得到原始文件、空格和所有内容的副本 我正在使用python 3和windows 8 import os import glob import re def cleanLeadingWhiteSpace(inputSrc, outputDest):

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

我正在使用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)

编辑后是否关闭了该文件
file.close()
您没有关闭文件对象,因此您永远不会只向缓冲区写入磁盘。在glob中文件的
末尾调用
outputFile.close()
,我在末尾添加了outputFile.close(),但结果仍然相同。谢谢你指出这一点,不管怎样,我都需要这样做。那么你确实生成了一个与输入文件相同的输出文件吗?diff-q输入输出报告文件是否相同?如果是这样的话,那么line.lstrip()就不会以某种方式执行。在文件上运行FC不会报告这两个文件之间的差异。这是令人困惑的,为什么保存文件就可以让它工作呢?谢谢@Adam Smith,非常感谢。问题仍然存在,我开始认为这是windows文件所有权/权限问题。