【发布时间】:2015-11-03 20:00:38
【问题描述】:
我有一个包含以下段落的文本文件:
上面的with语句会在嵌套代码块之后自动关闭文件。上面的 with 语句会在嵌套代码块之后自动关闭文件。上面的 with 语句会在嵌套代码块之后自动关闭文件。
上面的with语句会在没有嵌套代码块之后自动关闭文件。
现在,我想通过分隔段落的各行来修改文件,并将其保存在同一个文本文件中,如下所示:
上面的 with 语句会在嵌套代码块之后自动关闭文件。
上面的 with 语句会在嵌套代码块之后自动关闭文件。
上面的 with 语句会在嵌套代码块之后自动关闭文件。
上面的with语句会在没有嵌套代码块之后自动关闭文件。
我能做到,但有点复杂。我的代码如下:
try-1
file = open("file_path")
content = file.read()
file.close()
file = open("file_path", 'w')
a = content.replace('. ', '.\n')
file.write(a)
file.close()
try-2
file = open("file_path")
contents = file.readlines()
file.close()
b = []
for line in contents:
if not line.strip():
continue
else:
b.append(line)
b = "".join(b)
file = open("file_path", 'w')
file.write(b)
file.close()
我打开文件两次读取和两次写入,有没有更好的方法将行与文本文件中的段落分开,并将其写入同一个文本文件?
【问题讨论】:
标签: python