每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?
当前回答
我真的不想每次都输入\n, @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 + '\n')
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
其他回答
这是我自己想出来的解决方法为了系统地产生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 ""
我真的不想每次都输入\n, @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 + '\n')
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
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
or
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
请注意,该文件在Python 3中不支持,已被删除。你可以用open内置函数做同样的事情。
f = open('test.txt', 'w')
f.write('test\n')
实际上,当你使用多行语法时,就像这样:
f.write("""
line1
line2
line2""")
你不需要添加\n!
推荐文章
- 如何删除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中创建一个鼻涕虫?