How can I read text per line at Python and convert then to ASCII decimals?

320 Views Asked by At

What I have tried to do:

f = open('j:/text.txt', 'r')
lines = []
for line in f:
    lines.append(line)
print (''.join(str(ord(c)) for c in line))
print (line)
print (lines)

But this converts only the last line and ignores the previous ones.

2

There are 2 best solutions below

2
On BEST ANSWER

Try this:

with open('j:/text.txt', 'r', encoding="ascii") as file :
    lines = f.readlines()

for line in lines:
    line = line.replace("\n", "")
    print(''.join(str(ord(c)) for c in line))
3
On

I think you want to print every line's ASCII equivelant and the line itself. Put the first two print statements inside the for loop (Indent them once).

f = open('j:/text.txt', 'r')
lines = []
for line in f:
    lines.append(line)
    print (''.join(str(ord(c)) for c in line))
    print (line)
print (lines)