问题:每次在新行中将字符串写入文件

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

I want to append a newline to my string every time I call file.write(). What’s the easiest way to do this in Python?


回答 0

使用“ \ n”:

file.write("My String\n")

请参阅Python手册以获取参考。

Use “\n”:

file.write("My String\n")

See the Python manual for reference.


回答 1

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

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

You can do this in two ways:

f.write("text to write\n")

or, depending on your Python version (2 or 3):

print >>f, "text to write"         # Python 2.x
print("text to write", file=f)     # Python 3.x

回答 2

您可以使用:

file.write(your_string + '\n')

You can use:

file.write(your_string + '\n')

回答 3

如果您广泛使用它(很多书面文字),则可以将’​​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')

现在,它提供了一个附加功能wl,它可以执行您想要的操作:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

也许我缺少诸如不同的换行符(\ n,\ r,…)之类的东西,或者最后一行也以换行符结尾,但这对我有用。

If you use it extensively (a lot of written lines), you can subclass ‘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')

Now it offers an additional function wl that does what you want:

fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()

Maybe I am missing something like different newline characters (\n, \r, …) or that the last line is also terminated with a newline, but it works for me.


回答 4

你可以做:

file.write(your_string + '\n')

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

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

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

you could do:

file.write(your_string + '\n')

as suggested by another answer, but why using string concatenation (slow, error-prone) when you can call file.write twice:

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

note that writes are buffered so it amounts to the same thing.


回答 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")
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")

回答 6

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

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

Just a note, file isn’t supported in Python 3 and was removed. You can do the same with the open built-in function.

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

回答 7

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

笔记:

Unless write to binary files, use print. Below example good for formatting csv files:

def write_row(file_, *columns):
    print(*columns, sep='\t', end='\n', file=file_)

Usage:

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

Notes:


回答 8

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

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

Another solution that writes from a list using fstring

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

回答 9

这是我想出的解决方案,试图为自己解决此问题,以便系统地生成\ 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 ""

This is the solution that I came up with trying to solve this problem for myself in order to systematically produce \n’s as separators. It writes using a list of strings where each string is one line of the file, however it seems that it may work for you as well. (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 ""

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。