Hi, I write some data(Hello) in a file copy.txt. I read from the file copy.txt to convert the text "hello" to ASCII and then i store it in another file copy1.txt.
It saves the ascii like this in the file copy1.txt: 104101108108111.
Below is the ascii of each character:
104 - h
101 - e
108 - l
108 - l
111 - 0

Now i want to read from the copy1.txt to convert it back to string. My problem is that how will i know how many numbers represent a character. In this case the length of the ascii for each character is 3. But i want to cater a situation where the length of each character varies. Can someone help?

It's impossible. How can you tell if 101110 means 10 11 10 or 101 110 ? What you can do is format every char with 3 digits

>>> c = "\x0a"
>>> ord(c)
10
>>> str(ord(c))
'10'
>>> "{0:0>3}".format(ord(c))
'010'

ok lets say every character is 3 digits. i want to read from file and print each character. How to do this?

You can insert the ascii in the file using a csi (comma separate items) method, like

100,101,102,103

than getting from the file, having the comma , as the delimiter and than converting to characters. It would probably suite you better.

ok lets say every character is 3 digits. i want to read from file and print each character. How to do this?

Something like this.

def foo(filename, chunks):
    with open(filename) as f:
        numb_list = list(f.read())
        return [numb_list[i:i+chunks] for i in range(0, len(numb_list), chunks)]

lst = foo('data.txt', 3)
for item in lst:
    print chr(int(''.join(item)))

"""Output-->
h
e
l
l
o
"""

Saving your file like Lucaci Andrew (Lucaci Andrei) suggested is the best/safest solution.
You could even use a new line as a separator.

If you absolutely need a long numeric string, then use slicing like snippsat showed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.