1

I am trying to print a string which is human readable ascii but not getting any output. What am i missing?

import string
file = open("file.txt", "r")
data = file.read()
data = data.split("\n")
for line in data:
    if line not in string.printable:
        continue
    else:
        print line
anushka
  • 345
  • 4
  • 14

1 Answers1

1

If your file's content is text, you should read files like this:

import string
with open("file.txt", "r") as file:
    for line in file:
        if all( c in string.printable for c in line):
            print line

You must check every character individually to see if it is printable. There is another post about checking that string is printable: Test if a python string is printable

Also, you can read about context manager about how to open file right way: What is the most pythonic way to open a file?

J_R_
  • 21
  • 2
  • Yes, it is beter with generator. With square brackets python will construct list with lines as elements and it consumes additional memory. – J_R_ Jan 27 '19 at 11:52