每当我打电话给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
您可以使用:
file.write(your_string + '\n')
如果你广泛使用它(很多书面行),你可以继承'文件':
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')
return None
现在它提供了一个额外的功能,可以满足您的需求:
fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()
也许我错过了不同的换行符(\ n,\ n,...),或者最后一行也以换行符结束,但它对我有用。
file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
要么
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
你可以这样做:
file.write(your_string + '\n')
正如另一个答案所建议的那样,但为什么在可以调用file.write
两次时使用字符串连接(缓慢,容易出错):
file.write(your_string)
file.write("\n")
请注意,写入是缓冲的,因此它们相同。
只是一个注释,file
不支持Python 3
并被删除。您可以使用open
内置函数执行相同的操作。
f = open('test.txt', 'w')
f.write('test\n')
这是我想出的解决方案,以便系统地生成\ 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 ""
除非写入二进制文件,否则请使用print。下面的示例适用于格式化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) # newline
write_row(f, data[0], data[1])
笔记:
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/,PEP-3101*columns
在函数定义中 - 调度任意数量的参数列表 - 请参阅question on *args & **kwargs