每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?
当前回答
除非写入二进制文件,否则使用打印。下面的例子很适合格式化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])
您还可以使用partial作为一种更python化的方式来创建这种包装器。在下面的例子中,用预定义的kwargs打印行。
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])
注:
打印文档 “{},{}”。format(1, 'the_second') - https://pyformat.info/, PEP-3101 '\t' -制表符 函数定义中的*列-将任意数量的参数分派到列表-参见关于*args和**kwargs的问题
其他回答
如果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')
你可以在需要这种行为的特定地方装饰方法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')
如果你大量使用它(写了很多行),你可以子类化'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')
除非写入二进制文件,否则使用打印。下面的例子很适合格式化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])
您还可以使用partial作为一种更python化的方式来创建这种包装器。在下面的例子中,用预定义的kwargs打印行。
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])
注:
打印文档 “{},{}”。format(1, 'the_second') - https://pyformat.info/, PEP-3101 '\t' -制表符 函数定义中的*列-将任意数量的参数分派到列表-参见关于*args和**kwargs的问题
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录