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

2024-10-08 18:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 字符串代码textbinusr方式lineopen
2条回答

你应该边读边写。现在,你读了所有的书,只写了最后一本。应该是这样的:

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

只有最后一行会被写入,因为您在for循环中定义y,这意味着每次迭代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()

相关问题 更多 >

    热门问题