每次将字符串写入新行上的文件

问题描述 投票:195回答:9

每当我打电话给file.write()时,我想在我的字符串上添加换行符。在Python中最简单的方法是什么?

python newline
9个回答
225
投票

使用“\ n”:

file.write("My String\n")

请参阅the Python manual以供参考。


95
投票

您可以通过两种方式执行此操作:

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

62
投票

您可以使用:

file.write(your_string + '\n')

18
投票

如果你广泛使用它(很多书面行),你可以继承'文件':

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,...),或者最后一行也以换行符结束,但它对我有用。


5
投票
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")

4
投票

你可以这样做:

file.write(your_string + '\n')

正如另一个答案所建议的那样,但为什么在可以调用file.write两次时使用字符串连接(缓慢,容易出错):

file.write(your_string)
file.write("\n")

请注意,写入是缓冲的,因此它们相同。


1
投票

只是一个注释,file不支持Python 3并被删除。您可以使用open内置函数执行相同的操作。

f = open('test.txt', 'w')
f.write('test\n')

1
投票

这是我想出的解决方案,以便系统地生成\ 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 ""

0
投票

除非写入二进制文件,否则请使用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])

笔记:

© www.soinside.com 2019 - 2024. All rights reserved.