使用Python将文本文件中的空格转换为换行符

2024-03-28 23:45:07 发布

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

我有一个文本文件,如下所示:

15.9 17.2 18.6 10.5

我想用Python编辑此文件,使其看起来像这样:

15.9
17.2
18.6 
10.5

这意味着我需要用换行字符串替换空格字符串并保存文本。你知道吗

我试过了,但没用:

f = open("testfile.txt", "w")

for line in f:
    if ' ' in line:
        line2 = line.replace(' ' , '\n')
    print(line2)
for i in line2:
    f.write(line2(i))
f.close

line2的打印已经开始工作,但是我没有得到一个新的文本文件,其中空格被换行符替换。你知道吗

如何解决问题并产生所需的输出?你知道吗


Tags: 文件字符串in文本txt编辑forif
3条回答
with open("testfile.txt", "r") as r:
    with open("testfile_new.txt", "w") as w:
        w.write(r.read(.replace(' ' , '\n'))

试试这个

f = open("testfile.txt", "r")
text=f.read()
f.close()
f=open("testfile.txt", "w+")
text2=''
if ' ' in text:
    text2 = text.replace(' ' , '\n')
    print(text2)
    f.write(text2)
f.close()

您可以尝试使用字符串替换:

string = string.replace('\n', '').replace('\r', '')

首先:f.close()不存在。你知道吗

其次:尝试上面的代码。它将把空格替换为新行。你知道吗

相关问题 更多 >