问题:每次在新行中将字符串写入文件
我想在每次调用时在字符串后添加换行符file.write()。在Python中最简单的方法是什么?
回答 0
回答 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
回答 2
您可以使用:
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,…)之类的东西,或者最后一行也以换行符结尾,但这对我有用。
回答 4
你可以做:
file.write(your_string + '\n')正如另一个答案所建议的那样,但是为什么在您可以调用file.write两次时使用字符串连接(缓慢,容易出错):
file.write(your_string)
file.write("\n")
请注意,写操作是缓冲的,因此相当于同一件事。
回答 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
只是一个注释,file不受支持Python 3,已被删除。您可以使用open内置功能执行相同的操作。
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])笔记:
- 打印文件
- '{}, {}'.format(1, 'the_second')– https://pyformat.info/,PEP-3101
- ‘\ t’-制表符
- *columns在函数定义中-调度任意数量的参数以列出-请参阅有关* args和** kwargs的问题
回答 8
使用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 ""
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

