【发布时间】:2011-02-24 11:47:34
【问题描述】:
每次调用file.write() 时,我都想在字符串中添加一个换行符。在 Python 中最简单的方法是什么?
【问题讨论】:
每次调用file.write() 时,我都想在字符串中添加一个换行符。在 Python 中最简单的方法是什么?
【问题讨论】:
【讨论】:
file.write(f"{var1}\n")
您可以通过两种方式做到这一点:
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
【讨论】:
你可以使用:
file.write(your_string + '\n')
【讨论】:
file.write(f"my number is: {number}\n") 很好并且可读。
如果你广泛使用它(很多书面行),你可以继承'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 来满足你的需求:
with cfile('filename.txt', 'w') as fid:
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
也许我遗漏了不同的换行符(\n、\r、...)之类的东西,或者最后一行也以换行符结尾,但它对我有用。
【讨论】:
return None,因为首先,您不需要它,其次,当没有return 语句时,每个Python 函数默认返回None。
file 应该将其作为参数,在文件打开时应用。
你可以这样做:
file.write(your_string + '\n')
正如另一个答案所建议的那样,但是当您可以两次调用file.write 时,为什么要使用字符串连接(缓慢、容易出错):
file.write(your_string)
file.write("\n")
请注意,写入是缓冲的,所以它相当于同一件事。
【讨论】:
另一种使用 fstring 从列表中写入的解决方案
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
作为一个函数
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")
或
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
【讨论】:
除非写入二进制文件,否则使用 print。以下示例适用于格式化 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) # additional empty line
write_row(f, data[0], data[1])
注意事项:
'{}, {}'.format(1, 'the_second') - https://pyformat.info/, PEP-3101
*columns 在函数定义中 - 将任意数量的参数发送到列表 - 参见 question on *args & **kwargs
【讨论】:
请注意,file 不支持 Python 3 并已被删除。您可以使用 open 内置函数执行相同操作。
f = open('test.txt', 'w')
f.write('test\n')
【讨论】:
在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+"))
【讨论】:
这是我想出的解决方案,试图为自己解决这个问题,以便系统地生成 \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 ""
【讨论】:
with open(path, "w") as file: for line in strList: file.write(line + "\n")?这样你就可以删除所有的列表工作,检查,并且只有 3 行。
我真的不想每次都输入\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
【讨论】:
好的,这是一种安全的方法。
with open('example.txt', 'w') as f:
for i in range(10):
f.write(str(i+1))
f.write('\n')
这会将 1 到 10 的每个数字写成新的一行。
【讨论】:
您可以在需要此行为的特定位置装饰方法写入:
#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')
【讨论】:
通常您会使用 \n,但无论出于何种原因,在 Visual Studio Code 2019 个人版中它都不起作用。但是你可以使用这个:
# Workaround to \n not working
print("lorem ipsum", file=f) **Python 3.0 onwards only!**
print >>f, "Text" **Python 2.0 and under**
【讨论】:
如果 write 是回调,则可能需要自定义 writeln。
def writeln(self, string):
self.f.write(string + '\n')
它本身在一个自定义开瓶器中。查看此问题的答案和反馈:subclassing file objects (to extend open and close operations) in python 3
(上下文管理器)
我在使用 ftplib 从“基于记录”(FB80) 的文件中“检索行”时遇到了这个问题:
with open('somefile.rpt', 'w') as fp:
ftp.retrlines('RETR USER.REPORT', fp.write)
最后得到一个没有换行符的长记录,这可能是 ftplib 的问题,但很模糊。
所以变成了:
with OpenX('somefile.rpt') as fp:
ftp.retrlines('RETR USER.REPORT', fp.writeln)
它完成了这项工作。这是一个少数人会寻找的用例。
完整的声明(只有最后两行是我的):
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')
【讨论】: