每次将字符串写入文件的新行
- 2025-03-05 09:16:00
- admin 原创
- 87
问题描述:
我想在每次调用时在字符串中添加一个换行符file.write()
。在 Python 中执行此操作的最简单方法是什么?
解决方案 1:
使用“\n”:
file.write("My String
")
请参阅Python 手册以供参考。
解决方案 2:
您可以通过两种方式执行此操作:
f.write("text to write
")
或者,取决于你的 Python 版本(2 或 3):
print >>f, "text to write" # Python 2.x
print("text to write", file=f) # Python 3.x
解决方案 3:
您可以使用:
file.write(your_string + '
')
解决方案 4:
如果您广泛使用它(写了很多行),您可以将“文件”子类化:
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 + '
')
现在它提供了一个附加函数 wl 来执行您想要的操作:
with cfile('filename.txt', 'w') as fid:
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
也许我遗漏了一些东西,比如不同的换行符(\n、\r、...)或者最后一行也以换行符结束,但它对我来说有效。
解决方案 5:
你可以这样做:
file.write(your_string + '
')
正如另一个答案所建议的那样,但是当您可以调用两次时为什么要使用字符串连接(缓慢,容易出错)file.write
:
file.write(your_string)
file.write("
")
请注意,写入是缓冲的,因此它相当于同一件事。
解决方案 6:
另一种解决方案是使用 fstring 从列表中写入
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
for line in lines:
fhandle.write(f'{line}
')
并且作为一个函数
def write_list(fname, lines):
with open(fname, "w") as fhandle:
for line in lines:
fhandle.write(f'{line}
')
write_list('filename.txt', ['hello','world'])
解决方案 7:
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line
")
或者
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line
")
解决方案 8:
除非写入二进制文件,否则使用打印。以下示例适用于格式化 csv 文件:
def write_row(file_, *columns):
print(*columns, sep=' ', end='
', 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])
您还可以使用partial作为创建此类包装器的更 Python 化的方式。以下示例中row
使用print
了预定义的 kwargs。
from functools import partial
with open('file.csv', 'a+') as f:
row = partial(print, sep=' ', end='
', file=f)
row('header', 'phi:', PHI, 'serie no. 2', end='
')
row(data[0], data[1])
笔记:
打印文档
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/,PEP-3101'\t' - 制表符
*columns
在函数定义中 - 将任意数量的参数分派到列表 - 参见有关 args & *kwargs 的问题
解决方案 9:
请注意,file
不支持并已被删除。您可以使用内置函数Python 3
执行相同操作。open
f = open('test.txt', 'w')
f.write('test
')
解决方案 10:
好的,这是一个安全的方法。
with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('
')
这会将 1 到 10 的每个数字写入新行。
解决方案 11:
您可以使用 C 风格的字符串格式:
file.write("%s
" % "myString")
有关字符串格式化的更多信息。
解决方案 12:
我真的不想`
`每次都打字,而且@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 + '
')
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
解决方案 13:
这是我为了解决这个问题而想出的解决方案,目的是系统地生成 \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 "
" if the int entered isn't zero, otherwise "".
def cheekyNew(line):
if line != 0:
return "
"
return ""
解决方案 14:
您可以在需要此行为的特定位置装饰方法:
#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}
')
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')
解决方案 15:
对于我来说,在语句中使用append (a)
with看起来更容易:open()
`print()`
save_url = ". est.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+"))
解决方案 16:
如果您事先知道要添加哪些行,您可以这样做:
with open(file_path, 'w') as f:
text = "
".join(lines_list)
f.write(text)
解决方案 17:
通常你会使用,`
`但出于某种原因,在 Visual Studio Code 2019 Individual 中它不起作用。但你可以使用这个:
# Workaround to
not working
print("lorem ipsum", file=f) # Python 3.0 onwards only
print >>f, "Text" # Python 2.0 and under
解决方案 18:
如果 write 是一个回调,您可能需要自定义 writeln。
def writeln(self, string):
self.f.write(string + '
')
它本身位于自定义打开器内。请参阅此问题的答案和反馈:在 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 + '
')
解决方案 19:
实际上,当您使用多行语法时,如下所示:
f.write("""
line1
line2
line2""")
沒有需要添加`
`!
扫码咨询,免费领取项目管理大礼包!