如何在文件中写入新行或\ n

时间:2016-02-15 10:08:45

标签: python python-2.7

我有一个简单的代码,我想将2个文件写入1.我想在写完第一个文件后写一个新行或'\ n'。我尝试使用files.write但无法做到。有人可以帮助我吗?

这是我的代码:

files = run('ls -ltr /opt/nds')
files1 = run('ls -ltr /opt/web')
with open(section + "_tmp"+".txt", "w") as fo:
    fo.write(files)
with open(section + "_tmp"+".txt", "a") as fi:
    fi.write(files1)

这里,在写完文件之后,我想在将files1附加到同一个文件之前添加一个新行。

3 个答案:

答案 0 :(得分:2)

3种类似的方法:

1 - 连接2个列表并写一次

files = run('ls -ltr /opt/nds')
files1 = run('ls -ltr /opt/web')
to_write = files + files1
with open(section + "_tmp" + ".txt", "w") as f:
    f.write(to_write)

2 - 在写第二个列表之前写一个新行

files = run('ls -ltr /opt/nds')
files1 = run('ls -ltr /opt/web')
with open(section + "_tmp"+".txt", "w") as f:
    f.write(files)
    f.write("\n")
    f.write(files1)

3 - 一次列出所有文件而不是两次执行

files = run('ls -ltr /opt/(nds|web)')
with open(section + "_tmp"+".txt", "w") as f:
    f.write(files)

答案 1 :(得分:2)

为什么不尝试这样的东西来添加一行。

>>> f = open('C:\Code\myfile.txt','w')
>>> f.write('''
... my name
... is
... xyz
... ''')
18
>>> f.close()

内容将是"我的名字                        是                        xyz"

这里以f.write('''或f.write("""以''结尾)开头')或""")

前: -

f.write('''

             ''')

添加一行

答案 2 :(得分:1)

只需将os.linesep写入您的文件,然后从files1写入import os with open(section + "_tmp"+".txt", "a") as fi: fi.write(os.linesep) fi.write(files1) # Or simply fi.write(os.linesep + files1) ,如下面的代码段所示:

with

还没有理解两个单独的with语句,为什么不在一个import os files = run('ls -ltr /opt/nds') files1 = run('ls -ltr /opt/web') with open(section + "_tmp"+".txt", "w") as fo: fo.write(files) fo.write(os.linesep) fo.write(files1) 内写下所有数据:

<ul>