单线程在python中写入文件

问题描述 投票:1回答:3

如何在python中以更简单或单行的方式执行下面的写入文件任务?

#[PYTHON]
>>> log="/tmp/test_write.log"
>>> file = open(log, "a")
>>> file.write("x" * 10)
>>> file.write("\n")
>>> file.close()

在python中有一些这样的(bash / shell)吗?

#[SHELL]
log="/tmp/test_write.log"
printf "`printf 'x%0.s' {1..10}`\n" >> $log

注意: - 我在python中完全是noobie ...操作系统是RHEL 6/7和Python 3.3

python scripting
3个回答
4
投票

既然你需要调用writeclose,那么只写一行(不是完全疯狂的)就是用;来分隔两个命令,这很难读。

您可以使用with语句编写可读的双线程:

with open("/tmp/test_write.log", "a") as log:
    log.write("x"*10 + '\n')

文件是上下文管理器,使用with语句可确保在退出块后关闭文件。


2
投票
with open('file', 'w') as pf:
    pf.write('contents\n')

如果一条线很重要,那么使用起来非常好:

with open('file', 'w') as pf: pf.write('contents\n')

2
投票

你也可以使用print来做到这一点

由于文件对象通常包含write()方法,因此您需要做的就是将文件对象传递给其参数。

写/附加到如下文件:

with open("/tmp/test_write.log", 'a') as f:
    print("x"*10, file=f)
© www.soinside.com 2019 - 2024. All rights reserved.