Reputation: 21
I have to write substrings to a new file by reading from another file. The problem I am facing is that it only writes the last found substring. Here is what I've tried.
def get_fasta(site):
with open('file1.txt', 'r') as myfile:
data=myfile.read()
site = site-1
str1 = data[site:site+1+20]
temp = data[site-20:site]
final_sequence = temp+str1
with open('positive_results_sequences.txt', 'w') as my_new_file:
my_new_file.write(final_sequence + '\n')
def main():
# iterate over the list of IDS
for k,v in zip(site_id_list):
get_fasta(v)
if __name__ == '__main__':
main()
Upvotes: 0
Views: 56
Reputation: 56587
That's because you've opened the inner file in w
mode which recreates the file each time. So the end result is that only last write persists. You want to use a
mode (which stands for "append").
Also there are some other issues with your code. For example you open and close both files in each loop iteration. You should move file opening code outside and pass them as parameters:
def main():
with open('file1.txt', 'r') as myfile:
with open('positive_results_sequences.txt', 'a') as my_new_file:
for k,v in zip(site_id_list):
get_fasta(v, myfile, my_new_file)
Upvotes: 2