Python在字符后换行

Python在字符后换行,python,formatting,Python,Formatting,我想在文件中的一个点后换行 例如: Hello. I am damn cool. Lol 输出: Hello. I am damn cool. Lol 我试过了,但不知怎么的,它不起作用: f2 = open(path, "w+") for line in f2.readlines(): f2.write("\n".join(line)) f2.close() 你能帮我吗 我想要的不仅仅是一个换行符,我想要一个文件中每个点后面的换行符。它应该遍历整个文件,并

我想在文件中的一个点后换行

例如:

Hello. I am damn cool. Lol
输出:

Hello.
I am damn cool.
Lol
我试过了,但不知怎么的,它不起作用:

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

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


提前谢谢你

这就足够了:

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

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

这就足够了:

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

with open('file.txt', 'w') as f:
    f.write(contents.replace('. ', '.\n'))
您可以基于
将字符串存储在列表中,然后打印出列表

s = 'Hello. I am damn cool. Lol'
lines = s.split('.')
for line in lines:
  print(line)
如果执行此操作,输出将为:

Hello
 I am damn cool
 Lol
要删除前导空格,可以根据
(带空格)进行拆分,或者在打印时使用

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

# 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')
您可以基于
将字符串存储在列表中,然后打印出列表

s = 'Hello. I am damn cool. Lol'
lines = s.split('.')
for line in lines:
  print(line)
如果执行此操作,输出将为:

Hello
 I am damn cool
 Lol
要删除前导空格,可以根据
(带空格)进行拆分,或者在打印时使用

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

# 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')

可能是@Chris_Rands的复制品这行不通。。您刚刚在文件中写入了一个换行符。我想要一个点后的换行符。不仅仅是文件中的换行,了解
str.split()
;您需要将字符串拆分为一个以
结尾的子字符串列表,然后打印该列表。@Błotosmętek是的,但是其他单词会丢失。为了清楚起见,您想用换行符替换点后跟空格的模式吗?只替换点,你的输出线将以空格开始。可能是@Chris_Rands的重复。这不起作用。。您刚刚在文件中写入了一个换行符。我想要一个点后的换行符。不仅仅是文件中的换行,了解
str.split()
;您需要将字符串拆分为一个以
结尾的子字符串列表,然后打印该列表。@Błotosmętek是的,但是其他单词会丢失。为了清楚起见,您想用换行符替换点后跟空格的模式吗?只替换点,输出线将以空格开始。