[英]Convert spaces to newlines in text file using Python
I have a text file which looks like this: 我有一个文本文件,如下所示:
15.9 17.2 18.6 10.5
I want to edit this file in Python so that it looks like this: 我想用Python编辑这个文件,看起来像这样:
15.9
17.2
18.6
10.5
This means that I need to replace the space strings by newline strings and save the text. 这意味着我需要用换行符替换空格字符串并保存文本。
I tried this but it doesn't work: 我试过这个,但它不起作用:
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
The print for line2
is already working, but I don't get a new text file with spaces replaced by newlines. 对于打印line2
已经工作,但我没有得到与换行符替换空格的新文本文件。
How can I fix the problem and produce the desired output? 如何解决问题并产生所需的输出?
with open("testfile.txt", "r") as r:
with open("testfile_new.txt", "w") as w:
w.write(r.read(.replace(' ' , '\n'))
try like this instead 试着这样做
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', '')
Firstly: f.close() is not there. 首先: f.close()不存在。
Secondly: try above code. 其次:尝试上面的代码。 It will replace spaces to new lines. 它将空格替换为新线。
Example: 例:
with open("file1.txt", "r") as read_file:
with open("file2.txt", "w") as write_file:
write_file.write(read_file.read().replace(" ", '\n'))
Content of file1.txt: file1.txt的内容:
15.9 17.2 18.6 10.5
Content of file2.txt: file2.txt的内容:
15.9
17.2
18.6
10.5
NOTE: 注意:
Or you can use the split
and join
method instead of replace. 或者您可以使用split
和join
方法而不是替换。
write_file.write("\n".join(read_file.read().split()))
Use str.split
with str.join
将str.split
与str.join
str.split
使用
Ex: 例如:
with open("testfile.txt", "r") as infile:
data = infile.read()
with open("testfile.txt", "w") as outfile:
outfile.write("\n".join(data.split()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.