hal*_*dan 251
使用"\n":
file.write("My String\n")
Run Code Online (Sandbox Code Playgroud)
请参阅Python手册以供参考.
Gre*_*ill 101
您可以通过两种方式执行此操作:
f.write("text to write\n")
Run Code Online (Sandbox Code Playgroud)
或者,取决于您的Python版本(2或3):
print >>f, "text to write" # Python 2.x
print("text to write", file=f) # Python 3.x
Run Code Online (Sandbox Code Playgroud)
Kri*_*a K 67
您可以使用:
file.write(your_string + '\n')
Run Code Online (Sandbox Code Playgroud)
mat*_*use 22
如果你广泛使用它(很多书面行),你可以继承'文件':
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')
Run Code Online (Sandbox Code Playgroud)
现在它提供了一个额外的功能,可以满足您的需求:
fid = cfile('filename.txt', 'w')
fid.wl('appends newline charachter')
fid.wl('is written on a new line')
fid.close()
Run Code Online (Sandbox Code Playgroud)
也许我错过了不同的换行符(\n,\n,...),或者最后一行也以换行符结束,但它对我有用.
使用 fstring 从列表写入的另一种解决方案
lines = ['hello','world']
with open('filename.txt', "w") as fhandle:
for line in lines:
fhandle.write(f'{line}\n')
Run Code Online (Sandbox Code Playgroud)
并且作为一个函数
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'])
Run Code Online (Sandbox Code Playgroud)
你可以做:
file.write(your_string + '\n')
Run Code Online (Sandbox Code Playgroud)
正如另一个答案所建议的那样,但是为什么在您可以调用file.write
两次时使用字符串连接(缓慢,容易出错):
file.write(your_string)
file.write("\n")
Run Code Online (Sandbox Code Playgroud)
请注意,写操作是缓冲的,因此相当于同一件事。
除非写入二进制文件,否则请使用打印。下面的示例适用于格式化 csv 文件:
def write_row(file_, *columns):
print(*columns, sep='\t', end='\n', file=file_)
Run Code Online (Sandbox Code Playgroud)
用法:
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])
Run Code Online (Sandbox Code Playgroud)
笔记:
'{}, {}'.format(1, 'the_second')
- https://pyformat.info/ , PEP-3101*columns
在函数定义中 - 将任意数量的参数分派到列表中 - 请参阅关于 *args 和 **kwargs 的问题file_path = "/path/to/yourfile.txt"
with open(file_path, 'a') as file:
file.write("This will be added to the next line\n")
Run Code Online (Sandbox Code Playgroud)
要么
log_file = open('log.txt', 'a')
log_file.write("This will be added to the next line\n")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
579308 次 |
最近记录: |