简体   繁体   English

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

[英]Writing string to a file on a new line every time

I want to append a newline to my string every time I call file.write() .每次调用file.write()时,我都希望 append 换行到我的字符串。 What's the easiest way to do this in Python?在 Python 中,最简单的方法是什么?

Use "\n":使用“\n”:

file.write("My String\n")

See the Python manual for reference.请参阅Python 手册以供参考。

You can do this in two ways:您可以通过两种方式做到这一点:

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

or, depending on your Python version (2 or 3):或者,取决于您的 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')

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:现在它提供了一个额外的功能 wl 来做你想要的:

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

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.也许我错过了不同的换行符(\n、\r、...)之类的东西,或者最后一行也以换行符结尾,但它对我有用。

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两次时,为什么要使用字符串连接(慢,容易出错):

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

note that writes are buffered so it amounts to the same thing.请注意,写入是缓冲的,因此它相当于同一件事。

Another solution that writes from a list using fstring另一种使用 fstring 从列表中写入的解决方案

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

And as a function并且作为一个函数

def write_list(fname, lines):
    with open(fname, "w") as fhandle:
      for line in lines:
        fhandle.write(f'{line}\n')

write_list('filename.txt', ['hello','world'])
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")

Unless write to binary files, use print.除非写入二进制文件,否则请使用 print。 Below example good for formatting csv files:以下示例适用于格式化 csv 文件:

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)  # additional empty line
    write_row(f, data[0], data[1])

You can also use partial as a more pythonic way of creating this kind of wrappers.您还可以使用partial作为创建这种包装器的更 Pythonic 的方式。 In the example below, row is print with predefined kwargs.在下面的示例中, row是使用预定义的 kwargs print的。

from functools import partial


with open('file.csv', 'a+') as f:
    row = partial(print, sep='\t', end='\n', file=f)

    row('header', 'phi:', PHI, 'serie no. 2', end='\n\n')
    row(data[0], data[1])

Notes:笔记:

Just a note, file isn't supported in Python 3 and was removed.请注意, filePython 3中不受支持并已被删除。 You can do the same with the open built-in function.您可以使用open内置函数执行相同操作。

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

I really didn't want to type \n every single time and @matthause's answer didn't seem to work for me, so I created my own class我真的不想每次都输入\n并且@matthause 的答案似乎对我不起作用,所以我创建了自己的课程

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)

And here it is implemented在这里实现了

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 should show in the log file as这应该在日志文件中显示为

This is on the first line
This is on the second lineThis is still on the second line
This is on the third line

Using append (a) with open() on a print() statement looks easier for me:print()语句上使用append (a)open()对我来说看起来更容易:

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+"))

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.这是我想出的解决方案,试图为自己解决这个问题,以便系统地生成 \n 作为分隔符。 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.+) (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 ""

Ok, here is a safe way of doing it.好的,这是一种安全的方法。

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


This writes 1 to 10 each number on a new line.这会将 1 到 10 每个数字写入新行。

You can decorate method write in specific place where you need this behavior:您可以在需要此行为的特定位置装饰方法写入:

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

Usually you would use \n but for whatever reason in Visual Studio Code 2019 Individual it won't work.通常您会使用\n但无论出于何种原因在 Visual Studio Code 2019 个人版中它都不起作用。 But you can use this:但是你可以使用这个:

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

If write is a callback, you may need a custom writeln.如果 write 是回调,您可能需要自定义 writeln。

  def writeln(self, string):
        self.f.write(string + '\n')

Itself inside a custom opener.本身在自定义开瓶器中。 See answers and feedback for this question : subclassing file objects (to extend open and close operations) in python 3请参阅此问题的答案和反馈:在 python 3 中子类化文件对象(以扩展打开和关闭操作)

(Context Manager) (上下文管理器)

I faced this when using ftplib to "retrieve lines" from a file that was "record based" (FB80):我在使用 ftplib 从“基于记录”(FB80)的文件中“检索行”时遇到了这个问题:

with open('somefile.rpt', 'w') as fp:
     ftp.retrlines('RETR USER.REPORT', fp.write)

and ended up with one long record with no newlines, this is likely a problem with ftplib, but obscure.并以一个没有换行符的长记录结束,这可能是 ftplib 的问题,但晦涩难懂。

So this became:所以这变成了:

with OpenX('somefile.rpt') as fp:
     ftp.retrlines('RETR USER.REPORT', fp.writeln) 

It does the job.它完成了这项工作。 This is a use case a few people will be looking for.这是一些人会寻找的用例。

Complete declaration (only the last two lines are mine):完整的声明(只有最后两行是我的):

class OpenX:
    def __init__(self, filename):
        self.f = open(filename, 'w')

    def __enter__(self):
        return self.f

    def __exit__(self, exc_type, exc_value, traceback):
        self.f.close()

    def writeln(self, string):
        self.f.write(string + '\n')

为了支持多个操作系统,请使用: file.write(f'some strings and/or {variable}. {os.linesep}')

You could use C-style string formatting:您可以使用 C 风格的字符串格式:

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

More about String Formatting .更多关于字符串格式化

Actually, when you use the multiline syntax, like so:实际上,当你使用多行语法时,就像这样:

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

You don't need to add \n !您不需要添加\n

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM