每次在新行上写入字符串到文件

每次调用file.write()时,我都想在字符串后面追加一个换行符。在Python中最简单的方法是什么?

1069999 次浏览

你可以通过两种方式做到这一点:

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

使用“\ n”:

file.write("My String\n")

参考Python手册

你可以使用:

file.write(your_string + '\n')

如果你大量使用它(写了很多行),你可以子类化'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,…),或者最后一行也以换行符结束,但这对我来说是有效的。

注意,filePython 3中不支持,已被删除。你可以用open内置函数做同样的事情。

f = open('test.txt', 'w')
f.write('test\n')
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")

log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")

这是我自己想出来的解决方法为了系统地产生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 ""

你可以这样做:

file.write(your_string + '\n')

正如另一个答案所建议的那样,但是当你可以调用file.write两次时,为什么要使用字符串连接(缓慢,容易出错):

file.write(your_string)
file.write("\n")

注意,写操作是被缓冲的,所以两者是一样的。

除非写入二进制文件,否则使用打印。下面的例子很适合格式化csv文件:

def write_row(file_, *columns):
print(*columns, sep='\t', end='\n', file=file_)

用法:

PHI = 45
with open('file.csv', 'a+') as f:
write_row(f, 'header', 'phi:', PHI, 'serie no. 2')
write_row(f)  # additional empty line
write_row(f, data[0], data[1])

你也可以使用部分作为一种更python化的方式来创建这种包装器。在下面的例子中,row是带有预定义kwarg的print

from functools import partial




with open('file.csv', 'a+') as f:
row = partial(print, sep='\t', end='\n', file=f)


row('header', 'phi:', PHI, 'serie no. 2', end='\n\n')
row(data[0], data[1])

注:

另一个解决方案是使用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,而且@matthause的回答似乎对我不起作用,所以我创建了自己的类

class File():


def __init__(self, name, mode='w'):
self.f = open(name, mode, buffering=1)
        

def write(self, string, newline=True):
if newline:
self.f.write(string + '\n')
else:
self.f.write(string)

这就是它的实现

f = File('console.log')


f.write('This is on the first line')
f.write('This is on the second line', newline=False)
f.write('This is still on the second line')
f.write('This is on the third line')

这应该在日志文件中显示为

This is on the first line
This is on the second lineThis is still on the second line
This is on the third line

好的,这里有一个安全的方法。

with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('\n')




这将在新行中对每个数字写入1到10。

你可以在需要这种行为的特定地方装饰方法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')

对我来说,在print()语句中使用append (a)open()看起来更容易:

save_url  = ".\test.txt"


your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))


another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))


another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))

通常你会使用\n,但无论出于什么原因,在Visual Studio Code 2019 Individual中,它将不起作用。但是你可以用这个:

# Workaround to \n not working
print("lorem ipsum", file=f)  # Python 3.0 onwards only
print >>f, "Text"             # Python 2.0 and under

如果write是回调,则可能需要自定义writeln。

  def writeln(self, string):
self.f.write(string + '\n')

本身在自定义打开器中。参见此问题的答案和反馈:在python 3中子类化文件对象(扩展打开和关闭操作)

(上下文管理器)

我在使用ftplib“检索行”时遇到了这个问题。从一个“基于记录”的文件;(FB80):

with open('somefile.rpt', 'w') as fp:
ftp.retrlines('RETR USER.REPORT', fp.write)

最后得到一个没有换行符的长记录,这可能是ftplib的一个问题,但不清楚。

这就变成了:

with OpenX('somefile.rpt') as fp:
ftp.retrlines('RETR USER.REPORT', fp.writeln)

它起作用了。这是一些人正在寻找的用例。

完整的声明(只有最后两行是我的):

class OpenX:
def __init__(self, filename):
self.f = open(filename, 'w')


def __enter__(self):
return self.f


def __exit__(self, exc_type, exc_value, traceback):
self.f.close()


def writeln(self, string):
self.f.write(string + '\n')

以支持多个操作系统的使用: file.write(f'some strings and/or {variable}. {os.linesep}') < / p >

你可以使用c风格的字符串格式化:

file.write("%s\n" % "myString")

关于字符串格式化的更多信息。

实际上,当你使用多行语法时,就像这样:

f.write("""
line1
line2
line2""")

你不需要添加\n!