Home > Enterprise >  How can I check if a txt file only contains whitespaces
How can I check if a txt file only contains whitespaces

Time:07-03

with open('save.txt', 'r') as fname:
    data = fname.readlines()
    print(data)
    x = str(data)
    if x.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

I have tried this but it seems it doesnt work. I want to detect if a txt file only contains whitespaces and also /n if it is possible.

CodePudding user response:

The method readlines() returns a list with every single line. What you want is the read() method, which returns a single string for the whole file. The code would look like this:

with open('save.txt', 'r') as fname:
    data = fname.read()
    print(data)
    if data.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

Also, isspace() already considers \n and \t as whitespace.

CodePudding user response:

readlines() returns a list of strings. You need to check the element of data, not simply convert the list to str.

with open('save.txt', 'r') as fname:
    data = fname.readlines()
    only_whitespace = all(line.isspace() for line in data)
    if only_whitespace:
        print("only whitespaces")
    else:
        print("not only whitespaces")

CodePudding user response:

If you want to detect all whitespace characters (space, newline, tab, vertical space, carriage return...), then isspace might work for you, just read the file as a single string:

with open('save.txt', 'r') as fname:
    data = fname.read()
    print(data)
    if data.isspace():
        print("only whitespaces")
    else:
        print("not only whitespaces")

If you really only want space and newline, you could use a set operation:

with open('save.txt', 'r') as fname:
    data = set(fname.read())
    print(data)
    if data.issubset({' ', '\n'}):
        print("only whitespaces")
    else:
        print("not only whitespaces")
  • Related