每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?
当前回答
你可以使用:
file.write(your_string + '\n')
其他回答
你可以通过两种方式做到这一点:
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
除非写入二进制文件,否则使用打印。下面的例子很适合格式化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的问题
通常你会使用\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
如果你大量使用它(写了很多行),你可以子类化'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,…),或者最后一行也以换行符结束,但这对我来说是有效的。
好的,这里有一个安全的方法。
with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('\n')
这将在新行中对每个数字写入1到10。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录