Reputation: 211
I'm very new to programming & Python. Still currently working on my first program. I had a little bit of help from this forum a week ago or so, but now I'm stuck on another part of the program so I'd need some kind sole to help me out again :-)
In this example I have 2 files keyfile.dat
that contains the entire ascii charactor set, one character per line. They are the actual characters, NOT the codes.
test.txt
works like an index file. Each line contains a number that points to a line number within keyfile.dat
which in turn contains an ascii character. The code below prints letters of the alphabet, commas, question marks etc.. However it does not print spaces, carriage returns etc.. I guess this is because I am using str.strip
within the print
statement. If I do not use that command, instead of printing each character on the same line unless it reads a carriage return, it prints each character on a separate line. Basically this part of the program should print any character it is pointed to, regardless of what it is, and print it exactly as it is, just as like it was being typed.
---EDIT--- CODE REMOVED
Any ideas? & thanks in advance for any replies. Clinton.
Sample content of keyfile.dat
8
e
�
�
T
�
�
�
U
^V
�
^]
b
�
�
�
�
�
F
content test.txt:
14
203
163
38
52
163
38
188
231
11
38
231
242
208
74
163
38
163
231
Ouput using my code above:
T h i s , i s a t e s t ! O r i s i t ?
as you can see no spaces printed between words, and after ! there should be a carriage return.
Personally I think it is because of my print statement. I need to use .strip otherwise each character read from keyfile.dat gets printed on a new line. .strip to my knowledge removes spaces, carriage returns etc.. So if I read a carriage return & then try to print it, it gets stripped out because my print starement uses .strip.
Upvotes: 1
Views: 362
Reputation: 250871
Use with
statement for handling file, as it automatically closes the file for you:
with open('keyfile.dat') as f, open('test.txt') as i:
index = [int(line) for line in i) #apply int() here
keyfile = f.readlines()
for ind in index:
line = keyfile[ind]
if len(line) > 1:
print line[:-1],
elif len(line) == 1:
print line,
Upvotes: 2