Andy Andy - 1 year ago 86
Python Question

How to write the complete output of multi line strings in a text file using python?

I have the following text file containing the strings in the manner given below

trymf_001/trymrf_001_001
trymf_001/trymf_001_002
...
trymf_001/trymf_001_160
...
trymt_018/trymt_018_280


With the following code,

#!/usr/bin/env python
fo = open ("stt.text", "r")
for line in fo.readlines():
a = line.find('/')
str1 = line[0:9]
str2 = line[10:23]
y = str2 + ' ' + str1
print(y)
fo = open ("newstt.text", "w")
fo.write(y)
fo.close()


the output I get on the terminal screen when I print is:

trymrf_001_001 trymf_001
trymrf_001_002 trymf_001
...
trymf_001_160 trymf_001
...
trymt_018_280 trymt_018


But, I am getting only one line (the last one) in the new text file, while I
need all the lines.Thanks in advance.

Answer Source

Only the last line gets written because you are defining y inside the for loop which means on every iteration y gets redefined. You can try this instead

 fo = open ("stt.text", "r")
 y_list = [] # make new list to store all the data
 for line in fo.readlines():
     a = line.find('/')
     str1 = line[0:9]
     str2 = line[10:23]
     y = str2 + ' ' + str1
     y_list.append(y) # store all the data to the newly created list
     print(y)
 fo.close()
 fo = open ("newstt.text", "w")
 for lines in y_list:
     fo.write(lines+"\n") # write all the data from the list
 fo.close()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download