检查是否有一次写入的不同字符

时间:2016-07-09 13:06:52

标签: python python-3.x

我制作了一个小脚本,打开一个文件,获取它的大小,并根据需要将文件的大小写成零或一个。

def firstDeletion(filepath, txt):
    multiplier = getSize(filepath)
    with open(filepath, "w") as text_file:
         text_file.write(multiplier * txt)

之后,我希望它验证文件中只有给定的字符。我尝试这样做的方式如下,但我认为我的方法是错误的

def checkFile(file,phrase):
    with open(file, 'r') as resultfile:
        for line in resultfile:
            if (not phrase) in resultfile: #if found character different than phrase in resultfile
                return False
            else:
                return True  #No other char found

我认为它检查我的给定字符是否完全不在文本文件中,而不是检查是否还有另一个字符。我尝试一次读一个字符并检查它们是否匹配,但我收到了错误。而且我不喜欢这种方法,因为我担心如果我只读文件很大(比如1或2GB,脚本会因为内存而崩溃)

def checkFile(file,char):
    letter = file.read(1)
    if letter == char:
        return True
    else:
        return False

我得到的错误是: AttributeError: 'str' object has no attribute 'read'

我对python完全不熟悉,对我来说有点混乱。抱歉。

2 个答案:

答案 0 :(得分:2)

如果它只是你关心的一个角色(不是两行之间可以断开的单词或短语),那么你在第一次尝试时非常接近。

def checkFile(file,phrase):
    with open(file, 'r') as resultfile:
        for line in resultfile:
            if not all(char == phrase for char in line): # here you need to work with line, not the file object
                return False
            else:  # This else is redundant, because you can only return from a function once
                return True

我使用生成器表达式和改进的Python样式重写了这一点。您正在隐藏内置名称file并违反了几项PEP8建议。

def only_char_in_file(fp, target_char):
    with open(fp) as f:
        return all(char == target_char for line in f for char in line.strip())

更新上述两种方法都是懒惰处理文件(只有一行读入内存)。如果您的文件包含一个巨大的行,那么您需要一种特殊的方式来处理它。这个方法的工作速度明显慢于前两个,因为它意味着更多的IO和低级别的东西在Python中的工作速度比高级抽象要慢(因为后者实际上在C中运行)。无论如何:

import os


def only_char_in_file(fp, target_char):
    with open(fp) as f:
        char = f.read(1)
        while char:
            if char not in (target_char, os.linesep):
                return False
            char = f.read(1)
        return True

答案 1 :(得分:0)

def checkFile(file,phrase):
    with open(file, 'r') as resultfile:
        for line in resultfile:
            if (not phrase) in resultfile: #if found character different than phrase in resultfile
                return False
            else:
                return True  #No other char found

此函数的错误是语句if (not phrase) in resultfile,因为not关键字将布尔值转换为相反的值。所有空字符串均为False,所有其他字符串均为True。这意味着你在if语句中检查 resultfile 中的布尔值。

你在其他函数中获得AttributeError的原因是因为你在传递File对象时传递了一个String( resultfile 就是一个File对象)。

我会写这样的函数:

def check_file(file, phrase):
    with open(file, 'r') as result_file:
        for line in result_file.readlines():
            # Check that the line (with white space character removed) contains just 1 element
            # then check that the element is phrase.
            if len(set(line.strip())) == 1 and phrase in line:
                continue
            else:
                return False
    return True