每次调用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的问题
其他回答
通常你会使用\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
这是我自己想出来的解决方法为了系统地产生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 ""
你可以在需要这种行为的特定地方装饰方法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'])
对我来说,在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+"))
推荐文章
- 如何删除Python中的前导空白?
- python中的assertEquals和assertEqual
- 如何保持Python打印不添加换行符或空格?
- 为什么Python的无穷散列中有π的数字?
- Python 3.7数据类中的类继承
- 如何在PyTorch中初始化权重?
- 计数唯一的值在一列熊猫数据框架像在Qlik?
- 使用Pandas将列转换为行
- 从matplotlib中的颜色映射中获取单个颜色
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?