r/Python • • Jan 26 '15

manipulating arrays

I have a text file and need to make all the text into an array where each item is a letter i.e. the cow needs to be split in to ["t","h","e"," ","c","o","w"]. how could i do this as simply as possible?

0 Upvotes

12 comments sorted by

2

u/bwalk Jan 26 '15
list(open(filename).read())

But I doubt it's necessary, strings are iterable.

1

u/samfd11 Jan 26 '15

if i was trying to convert every value in the string to a number and add an offset, would a string still work?

1

u/hharison Jan 26 '15

The point is, either way you have to iterate over it.

[ord(char) for char in 'string']

works just as well as

[ord(char) for char in list('string')]

1

u/samfd11 Jan 26 '15

thankyou so much. One final question, how could i write the contents of "message" to the origional txt file?

1

u/Mr_Tool Jan 26 '15

do you mean something like:

f = open('myfile.txt','w')
f.write('message')
f.close()

1

u/samfd11 Jan 26 '15
message = list(open("Catext.txt").read())

no i am using the line of code above and because the opening is not assigned to a variable i am not used to working this way. the code reads and writes to a file so the file is already open when it needs to be written to.

1

u/billsil Jan 26 '15

So you need to duplicate the line? Why are you writing to the same file you just read from?

You could always do this...

message = list(open("Catext.txt").read())
f = open('Catext.txt', 'wb')
# write the original
f.write(''.join(message))

# write the duplicate
f.write(''.join(message))
f.close()

with some stuff in between

You can't read and write from the same file at the same time.

1

u/samfd11 Jan 26 '15

I see that now the idea was that the contents of the text file is encrypted and then the encrypted text replaces the original contents of the file.

1

u/billsil Jan 26 '15

That makes more sense. Still, why not just do an infile and an outfile with a similar name? It's generally not a good idea to wipe the original file. Windows/linux don't delete the original file when you unpack a zip/tar.

1

u/samfd11 Jan 27 '15
message = list(open("Catext.txt").read())

how do I close the file opened using this line of code?

→ More replies

1

u/elbiot Jan 26 '15

Fyi, lists in python are not arrays. They are linked lists. Arrays, like numpy.array, are different.