简体   繁体   中英

i want new line after one list in 2D Array in python with a file text

this is my code

list = [["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]
    
    file = open("codons.txt","w") 
    
    for i in list:
        
        for j in i:
         file.write(j)
         file.write(" ")

this is the desired output

UUU UCU UAU UGU

UUC UCC UAC UGC

You can do this:

The below code will concatenate all the values in each row, then add \n to it and write to file.

my_list=[["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]

with open("codons.txt", "w") as f_out:
    for line in my_list:
        f_out.write(' '.join(line) + '\n')

Output of this will be:

UUU UCU UAU UGU
UUC  UCC  UAC  UGC

Note here that I am not removing the leading and trailing spaces. If you want the leading and trailing spaces to be removed, the join() statement needs to be modified.

If you want the leading and trailing spaces to be stripped so the output looks like this:

UUU UCU UAU UGU
UUC UCC UAC UGC

Then use the below code instead:

my_list=[["UUU","UCU", "UAU", "UGU"],["UUC", " UCC ", "UAC", " UGC"]]

with open("codons.txt", "w") as f_out:
    for line in my_list:
        f_out.write(' '.join([item.strip() for item in line]) + '\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM