2

How can I save a 2-dimensional array into a text file with python? I tried to do it as follows, but I get an error:

readcodon= open("codon.txt","r")
triplets=readcodon.read().split()
for i in range(0,len(triplets)):
   A=np.array(triplets, dtype=None)
readcodon.write(A)

This is the error message:

readcodon.write(A)

TypeError: write() argument must be str, not numpy.ndarray

Here is a sample of codon.txt:

TTT TCT TAT TGT TTC 

The expected output in the file text:

[TTT, TCT, TAT, TGT, TTC ]
2
  • I edit it @yoonghm Commented Feb 15, 2021 at 22:50
  • I edit it @yoonghm Commented Feb 15, 2021 at 23:04

3 Answers 3

2

For readability and simplicity, you can just use the numpuy.savetxt() function of numpy.

This method is used to save an array to a text file. This is an example of writing a 2d array into a file:

# Python program explaining 
# savetxt() function 
import numpy as geek 

x = geek.array([[1,2],[3,4]])
print("x is:") 
print(x) 

# X is an array 
c = geek.savetxt('geekfile.txt', x, delimiter =', ') 
a = open("geekfile.txt", 'r')# open file in read mode 

print("the file contains:") 
print(a.read()) 

Also, take a look at the official documentation, and at the geeksforgeeks numpuy.savetxt() guide for any doubts and clarifications.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much for your help @simonedimaria
1

Say you have a file codon.txt with the following contents:

TTT TCT TAT TGT TTC 

I don't think you need to redudantly convert the list returned from split into a numpy array to achieve your desired output:

with open('codon.txt', 'r+') as codon_file:
    triplets = codon_file.read().split()
    codon_file.seek(0)
    codon_file.write(f"[{', '.join(triplets)}]")
    codon_file.truncate()

The contents of codon.txt after running above:

[TTT, TCT, TAT, TGT, TTC]

If you absolutely need the output to have the extra space after the last element of the list i.e:

[TTT, TCT, TAT, TGT, TTC ]

You can add the space before the end of the f-string:

codon_file.write(f"[{', '.join(triplets)} ]")
#                                        ^
#                                        |
#                                        space character

Comments

0

write() function wants a string. You can make a string out of your array or you can use numpys built-in write function instead:

np.savetxt(readcodon,A)

I think there is also a mistake in your for loop, it does three times the same thing, maybe you want to use your loop index i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.