1

I have a simple code where i wanted to write 2 files into 1. I wanted to write a new line or '\n' after the first file is written. I tried using files.write but unable to do it. Can someone help me in this?

This is my code:

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)

Here, after the files is written, i wanted to add a new line before files1 is appended to the same file.

Roshan r
  • 522
  • 2
  • 11
  • 30
  • What do you mean by "section" in your code? – Manjunath N Feb 15 '16 at 10:10
  • Possible duplicate of [writing string to a file on a new line everytime?](http://stackoverflow.com/questions/2918362/writing-string-to-a-file-on-a-new-line-everytime) – martin Feb 15 '16 at 10:14

3 Answers3

2

3 similar approaches:

1 - Concatenate 2 lists and write once

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 - Write a new line before writing the second list

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 - List all files at once rather than doing them twice

files = run('ls -ltr /opt/(nds|web)')
with open(section + "_tmp"+".txt", "w") as f:
    f.write(files)
Lim H.
  • 9,870
  • 9
  • 48
  • 74
2

Why dont you try something like this to add a line.

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

The contents will be " my name is xyz "

Here begin with f.write(''' or f.write(""" and end with ''') or """)

Ex:-

f.write('''

             ''')

adds a line

Mukund Gandlur
  • 861
  • 1
  • 12
  • 35
1

Simply write os.linesep into your file before writing into it from files1 as in code snippet below:

import os

with open(section + "_tmp"+".txt", "a") as fi:
    fi.write(os.linesep)
    fi.write(files1)
    # Or simply fi.write(os.linesep + files1)

Also didn't catch idea of two separate with statements, why not to write all data within one 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)
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82