pythonpython-3.xfilewriter

python doesn't append each line but skips some


I have a complete_list_of_records which has a length of 550

this list would look something like this:

  1. Apples

  2. Pears

  3. Bananas

The issue is that when i use:

 with open("recordedlines.txt", "a") as recorded_lines:
      for i in complete_list_of_records:
            recorded_lines.write(i)

the outcome of the file is 393 long and the structure someplaces looks like so

  1. Apples

  2. PearsBananas

  3. Pineapples

I have tried with "w" instead of "a" append and manually inserted "\n" for each item in the list but this just creates blank spaces on every second row and still som rows have the same issue with dual lines in one.

Anyone who has encountered something similar?


Solution

  • From the comments seen so far, I think there are strings in the source list that contain newline characters in positions other than at the end. Also, it seems that some strings end with newline character(s) but not all.

    I suggest replacing embedded newlines with some other character - e.g., underscore.

    Therefore I suggest this:

    with open("recordedlines.txt", "w") as recorded_lines:
          for line in complete_list_of_records:
                line = line.rstrip() # remove trailing whitespace
                line = line.replace('\n', '_') # replace any embedded newlines with underscore
                print(line, file=recorded_lines) # print function will add a newline