每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?
当前回答
你可以通过两种方式做到这一点:
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
其他回答
你可以在需要这种行为的特定地方装饰方法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')
另一个解决方案是使用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”:
file.write("My String\n")
参考Python手册。
你可以使用:
file.write(your_string + '\n')
通常你会使用\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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录