[英]replace new line in a different file with an underscore (without using with)
I posted a question yesterday in similar regards to this but didn't quite gauge the response I wanted because I wasn't specific enough. 昨天,我以与此类似的方式发布了一个问题,但由于我不够具体,所以未能完全评估我想要的答复。 Basically the function takes a .txt file as the argument and returns a string with all \\n characters replaced with an '_' on the same line. 基本上,该函数将.txt文件作为参数,并返回在同一行上所有\\ n字符均替换为'_'的字符串。 I want to do this without using WITH. 我想不使用WITH来做到这一点。 I thought I did this correctly but when I run it and check the file, nothing has changed. 我以为我做对了,但是当我运行它并检查文件时,没有任何改变。 Any pointers? 有指针吗?
This is what I did: 这是我所做的:
def one_line(filename):
wordfile = open(filename)
text_str = wordfile.read().replace("\n", "_")
wordfile.close()
return text_str
one_line("words.txt")
but to no avail. 但无济于事。 I open the text file and it remains the same. 我打开文本文件,它保持不变。
The contents of the textfile are: 文本文件的内容为:
I like to eat
pancakes every day
and the output that's supposed to be shown is: 并且应该显示的输出是:
>>> one_line("words.txt")
’I like to eat_pancakes every day_’
The fileinput
module in the Python standard library allows you to do this in one fell swoop. Python标准库中的fileinput
模块允许您fileinput
做到这一点。
import fileinput
for line in fileinput.input(filename, inplace=True):
line = line.replace('\n', '_')
print(line, end='')
The requirement to avoid a with
statement is trivial but rather pointless. 避免使用with
语句的要求微不足道,但毫无意义。 Anything which looks like 任何看起来像
with open(filename) as handle:
stuff
can simply be rewritten as 可以简单地重写为
try:
handle = open(filename)
stuff
finally:
handle.close()
If you take out the try
/ finally
you have a bug which leaves handle
open if an error happens. 如果您try
/ finally
您将遇到一个错误,如果发生错误,该错误将使handle
打开状态。 The purpose of the with
context manager for open()
is to simplify this common use case. with
上下文管理器的open()
是简化此常见用例。
You are missing some steps. 您缺少一些步骤。 After you obtain the updated string, you need to write it back to the file, example below without using with
获取更新的字符串后,需要将其写回到文件中,下面的示例中不使用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)
Or using with
或with
with open("file.txt",'w') as wordfile:
#Write the updated string to the file
wordfile.write(s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.