Skip to main content
 首页 » 编程设计

python之我如何写一个新行或\n到文件中

2025年05月04日27xxx_UU

我有一个简单的代码,我想将 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 种类似的方法:

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)