每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?
当前回答
你可以在需要这种行为的特定地方装饰方法write:
#Changed behavior is localized to single place.
with open('test1.txt', 'w') as file:
def decorate_with_new_line(method):
def decorated(text):
method(f'{text}\n')
return decorated
file.write = decorate_with_new_line(file.write)
file.write('This will be on line 1')
file.write('This will be on line 2')
file.write('This will be on line 3')
#Standard behavior is not affected. No class was modified.
with open('test2.txt', 'w') as file:
file.write('This will be on line 1')
file.write('This will be on line 1')
file.write('This will be on line 1')
其他回答
你可以通过两种方式做到这一点:
f.write("text to write\n")
或者,取决于你的Python版本(2或3):
print >>f, "text to write" # Python 2.x
print("text to write", file=f) # Python 3.x
如果你大量使用它(写了很多行),你可以子类化'file':
class cfile(file):
#subclass file to have a more convienient use of writeline
def __init__(self, name, mode = 'r'):
self = file.__init__(self, name, mode)
def wl(self, string):
self.writelines(string + '\n')
现在它提供了一个额外的函数wl来做你想要的:
with cfile('filename.txt', 'w') as fid:
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
也许我遗漏了一些东西,比如不同的换行符(\n, \r,…),或者最后一行也以换行符结束,但这对我来说是有效的。
你可以这样做:
file.write(your_string + '\n')
正如另一个答案所建议的,但为什么在可以调用文件时使用字符串连接(缓慢,容易出错)。写两次:
file.write(your_string)
file.write("\n")
注意,写操作是被缓冲的,所以两者是一样的。
另一个解决方案是使用fstring从列表中写入
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
作为一个函数
def write_list(fname, lines):
with open(fname, "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
write_list('filename.txt', ['hello','world'])
这是我自己想出来的解决方法为了系统地产生n作为分离器。它使用一个字符串列表,其中每个字符串是文件的一行,但它似乎也可以为您工作。(Python 3 +)。
#Takes a list of strings and prints it to a file.
def writeFile(file, strList):
line = 0
lines = []
while line < len(strList):
lines.append(cheekyNew(line) + strList[line])
line += 1
file = open(file, "w")
file.writelines(lines)
file.close()
#Returns "\n" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
if line != 0:
return "\n"
return ""