每次调用file.write()时,我都想在字符串中添加换行符。在Python中最简单的方法是什么?


当前回答

这是我自己想出来的解决方法为了系统地产生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 ""

其他回答

你可以通过两种方式做到这一点:

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')

你可以使用c风格的字符串格式化:

file.write("%s\n" % "myString")

更多关于字符串格式。

这是我自己想出来的解决方法为了系统地产生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 ""

为了支持多种操作系统的使用: 文件。写(f'some字符串和/或{variable}。{os.linesep}”)