如何使用python在文本文件中编写多行字符串的完整输出?

时间:2017-02-07 09:15:59

标签: python string python-2.7 python-3.x machine-learning

我有以下文本文件,其中包含以下面给出的方式的字符串

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

使用以下代码

#!/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()  

打印时我在终端屏幕上看到的输出是:

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

但是,我在新文本文件中只获得一行(最后一行),而我 需要所有的线路。

2 个答案:

答案 0 :(得分:0)

你应该在阅读时写下它。现在,你正在阅读所有这些,并且只写最后一个。看起来应该是这样的:

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

答案 1 :(得分:0)

只有最后一行被写入,因为您在y循环中定义for,这意味着每次迭代y都被重新定义。你可以试试这个

 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()