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

时间:2010-05-27 03:56:12

标签: python newline

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

15 个答案:

答案 0 :(得分:221)

使用“\ n”:

file.write("My String\n")

请参阅the Python manual以供参考。

答案 1 :(得分:94)

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

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

答案 2 :(得分:62)

您可以使用:

file.write(your_string + '\n')

答案 3 :(得分:18)

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

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

答案 4 :(得分:8)

另一种使用fstring从列表写入的解决方案

lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
  for line in lines:
    fhandle.write(f'{line}\n')

答案 5 :(得分: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")

答案 6 :(得分:2)

您可以这样做:

file.write(your_string + '\n')

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

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

请注意,写操作是缓冲的,因此等同于同一件事。

答案 7 :(得分:1)

只需注意,file中不支持Python 3,并已将其删除。您可以使用open内置函数执行相同的操作。

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

答案 8 :(得分: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 ""

答案 9 :(得分:1)

好的,这是一种安全的方法。

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


这会将 1 到 10 每个数字写在一个新行上。

答案 10 :(得分:1)

append (a) 语句中使用 open()print() 对我来说看起来更容易:

save_url  = ".\test.txt"

your_text = "This will be on line 1"
print(your_text, file=open(save_url, "a+"))

another_text = "This will be on line 2"
print(another_text, file=open(save_url, "a+"))

another_text = "This will be on line 3"
print(another_text, file=open(save_url, "a+"))

答案 11 :(得分:0)

除非写入二进制文件,否则使用打印。下面的示例非常适合格式化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])

注意:

答案 12 :(得分:0)

我真的不想每次都输入\n并且@matthause's answer似乎不适合我,所以我创建了自己的课程

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

答案 13 :(得分:0)

您可以在需要此行为的特定位置装饰方法 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')  

答案 14 :(得分:0)

通常您会使用 \n,但无论出于何种原因,它在 Visual Studio Code 2019 Individual 中都不起作用。但是你可以使用这个:

# Workaround to \n not working
print("lorem ipsum", file=f) **Python 3.0 onwards only!**
print >>f, "Text" **Python 2.0 and under**