Python在ch之后换行

2024-05-15 21:58:04 发布

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

我想在文件中的点后面加一个换行符。在

例如:

Hello. I am damn cool. Lol

输出:

^{pr2}$

我就这样试过了,但不知怎么没用:

f2 = open(path, "w+")
    for line in f2.readlines():
        f2.write("\n".join(line))
    f2.close()

你能帮我吗?在

我要的不仅仅是换行符,我还要在一个文件中的每个点后面加一个换行符。它应该遍历整个文件,并在每个点之后生成新行。在

提前谢谢你!在


Tags: 文件pathinhelloforlineopenam
2条回答

这就足够了:

with open('file.txt', 'r') as f:
    contents = f.read()

with open('file.txt', 'w') as f:
    f.write(contents.replace('. ', '.\n'))

您可以根据.将字符串split存储在一个列表中,然后打印出该列表。在

s = 'Hello. I am damn cool. Lol'
lines = s.split('.')
for line in lines:
  print(line)

如果您这样做,输出将是:

^{pr2}$

要删除前导空格,可以基于.(带空格)拆分,或者在打印时使用^{}。在

因此,要对文件执行此操作:

# open file for reading
with open('file.txt') as fr:
  # get the text in the file
  text = fr.read()
  # split up the file into lines based on '.'
  lines = text.split('.')

# open the file for writing
with open('file.txt', 'w') as fw:
  # loop over each line
  for line in lines:
    # remove leading whitespace, and write to the file with a newline
    fw.write(line.lstrip() + '\n')

相关问题 更多 >