0

I'm using Python 2.7 and trying to read from pipe-delimited Src file, adding string to each line and writing the string to another file.

def createInfoTypeFile(srcDir, targetFile, startWith):
  for subdir, dir, files in os.walk(srcDir):
      for file in files:
          fpath = os.path.join(subdir, file)
          if (fpath.endswith('.SAP')):
              f = open(fpath, 'r')
              lines = f.readlines()
              for line in lines:
                  if line.startswith(startWith):
                      line1 = line + "|key|false\n"
                      targetFile.write(line1)

I call the above code, passing it the src, target files and a starting string

The string gets appended to the line, but after a new line

a|b|
|key|false

'key|false|' - is what i'm adding to each Line read, but after newline I want |key|false added to the original line w/o newline

i.e.

a|b|key|false
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Karan Alang
  • 869
  • 2
  • 10
  • 35
  • I think `open(filename,'r').read().split('\n')` can help you sort the issue out - check [this](https://stackoverflow.com/a/12330540/4092588) for further info – Antonino Apr 19 '19 at 23:49
  • Possible duplicate of [Reading a file without newlines](https://stackoverflow.com/questions/12330522/reading-a-file-without-newlines) – Antonino Apr 19 '19 at 23:52

1 Answers1

1
line1 = line.rstrip() + "|key|false\n" 

Strip out the extra newline from the original before appending.

rdas
  • 20,604
  • 6
  • 33
  • 46