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


当前回答

你可以使用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 ""
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")

实际上,当你使用多行语法时,就像这样:

f.write("""
line1
line2
line2""")

你不需要添加\n!

你可以在需要这种行为的特定地方装饰方法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')  

好的,这里有一个安全的方法。

with open('example.txt', 'w') as f:
 for i in range(10):
  f.write(str(i+1))
  f.write('\n')


这将在新行中对每个数字写入1到10。