单线程在python中写入文件

时间:2017-12-22 11:52:40

标签: python scripting

如何在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

4 个答案:

答案 0 :(得分:4)

由于您需要调用writeclose,因此只编写一行的唯一(非完全疯狂)方法是将两个命令分开;,这很可怕阅读。

你可以用with语句写一个可读的双线:

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

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

答案 1 :(得分:2)

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

如果一行是重要的,那么使用它就完全没问题了:

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

答案 2 :(得分:2)

您也可以使用print

执行此操作

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

写入/附加到如下文件:

with open("/tmp/test_write.log", 'a') as f:
    print("x"*10, file=f)

答案 3 :(得分:0)

我在另一次搜索中遇到了这个问题。有一种更简单的(imo)方法;

from the docs

    ideal_hash = {
          :full_name => ["Leanne Graham", "another name", "another name", "etc"]
          :email => ["Sincere@april.biz", "some email", "another one", "etc"]
       }

所以,你可以用一行来写;

>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'