用下划线替换其他文件中的新行(不使用with)

2024-09-28 22:48:59 发布

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

我昨天发布了一个类似的问题,但没有完全衡量我想要的答复,因为我不够具体。基本上,该函数以.txt文件作为参数,并返回一个字符串,其中所有\n字符都替换为同一行上的“\”。我想不使用WITH来做这个。我以为我做得对,但当我运行它并检查文件时,什么都没有改变。有什么建议吗?你知道吗

我就是这么做的:

def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

one_line("words.txt")

但无济于事。我打开文本文件,它保持不变。你知道吗

文本文件的内容包括:

I like to eat
pancakes every day

应该显示的输出是:

>>> one_line("words.txt")
’I like to eat_pancakes every day_’

Tags: 文件totexttxtlinefilenameonelike
3条回答

你错过了一些步骤。获取更新后的字符串后,需要将其写回文件,下面的示例不使用with

def one_line(filename):
    wordfile = open(filename)
    text_str = wordfile.read().replace("\n", "_")
    wordfile.close()
    return text_str

def write_line(s):
    # Open the file in write mode
    wordfile = open("words.txt", 'w')

    # Write the updated string to the file
    wordfile.write(s)

    # Close the file
    wordfile.close()

s = one_line("words.txt")
write_line(s)

或者使用with

with open("file.txt",'w') as wordfile:

    #Write the updated string to the file
    wordfile.write(s)

Python标准库中的^{}模块允许您一下子做到这一点。你知道吗

import fileinput

for line in fileinput.input(filename, inplace=True):
    line = line.replace('\n', '_')
    print(line, end='')

避免with语句的要求很简单,但却毫无意义。任何看起来像

with open(filename) as handle:
    stuff

可以简单地重写为

try:
    handle = open(filename)
    stuff
finally:
    handle.close()

如果取出try/finally,则会出现一个错误,如果发生错误,handle就会打开。用于open()with上下文管理器的目的是简化这个常见用例。你知道吗

使用^{}可以通过以下方式实现您想要的:

from pathlib import Path

path = Path(filename)
contents = path.read_text()
contents = contents.replace("\n", "_")
path.write_text(contents)

相关问题 更多 >