-1
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.

AfterHover
  • 97
  • 2
  • 12

3 Answers3

3

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.

1

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")
Haoliang
  • 1,184
  • 4
  • 11
1

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")
mozway
  • 194,879
  • 13
  • 39
  • 75