anushka
anushka

Reputation: 345

trying to print human readable ascii string

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

Upvotes: 1

Views: 438

Answers (1)

J_R_
J_R_

Reputation: 21

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?

Upvotes: 1

Related Questions